How-To's > How do I add sound to my application?

Version: JavaFX 1.3

You can incorporate sound into your application by using the MediaPlayer and Media classes as shown in the following.

import javafx.scene.media.*;

def music = Media {source: "http://<myMediaServer>/<myAudioFile>"};
var myPlayer = MediaPlayer{ media: music};

When the MediaPlayer object is added in your application, you can use the following instance variables and functions of the MediaPlayer class to control audio playback in your application:

  • pause() - Pauses playing.
  • play() - Starts or resumes playing.
  • stop() - Stops playing, resets to the beginning of the media, and resets the play count.
  • autoPlay - If autoPlay is true, playing will start as soon as possible.
  • paused - Indicated if the player has been paused, either programmatically, by the user, or because the media has finished playing.

As the simplest task you can start playing the sound on the application launch and loop the time cycle infinitely.

import javafx.scene.media.*;

def music = Media {source: "http://<myMediaServer>/<myAudioFile>"};
var myPlayer = MediaPlayer{ 
     media: bind music
     autoPlay: true //the media starts as soon as possible
     repeatCount: MediaPlayer.REPEAT_FOREVER //infinite time cycle for the media
};

In addition, you can use a visual UI control to pause, stop, and resume the playback.

def imagePlay = Image {url: "{__DIR__}buttonPlay.png"};
def imagePause = Image {url: "{__DIR__}buttonPause.png"};

var controlButton = ImageView {
    image: bind if (myPlayer.paused)
        then imagePlay
        else imagePause
    onMouseClicked: function (e) {
        if (myPlayer.paused){
        // resume or start playing if the player is paused
        myPlayer.play();
        }
        else {
        // pause playing if the player is run
        myPlayer.pause();
        }
    }
};

You can use the same Play/Pause button to control both the audio playback and animation timeline.

Tips

  • Although you use the same classes of the media API to incorporate video and audio content into your application, you don't need to create a MediaView object in your code. The MediaView class is an extension of the Node class. Also, it is used to arrange the media object on the scene and apply transformations or effects. Because sound doesn't have a visual constituent, you don't need to use the MediaView class.
  • Use the onEndOfMedia function of the MediaPlayer class to perform an action when the player reaches the end of media.

Examples

Related How-To Topics

API Documentation

Last Updated: April 2010
[Return to How-To's Home]