Playing Audio

JavaFX Playing Audio with JavaFX Overview, Install Java, Install Eclipse, JavaFX with Eclipse, JavaFX Architecture, JavaFX Application Structure, First JavaFX Application etc.

Playing Audio

Playing Audio

We can load the audio files with extensions like .mp3,.wav and .aifff by using JavaFX Media API. We can also play the audio in HTTP live streaming format. It is the new feature introduced in JavaFX 8 which is also known as HLS.

Playing audio files in JavaFX is simple. For this purpose, we need to instantiate javafx.scene.media.Media class by passing the audio file path in its constructor. The steps required to be followed in order to play audio files are described below.

Instantiate the javafx.scene.media.Media class by passing the location of the audio file in its constructor. Use the following line of code for this purpose.

  1. Media media = new Media("http://path/file_name.mp3");

Pass the Media class object to the new instance of javafx.scene.media.MediaPlayer object.

  1. Mediaplayer mediaPlayer = new MediaPlayer(media);  

Invoke the MediaPlayer object's play() method when onReady event is triggered.

  1. MediaPlayer.setAutoPlay(true);  

The Media File can be located on a web server or on the local file system. SetAutoPlay() method is the short-cut for setting the setOnReady() event handler with the lambda expression to handle the event.

Example

In the following example, the audio file located at "/home/hpnmaratt/Downloads/test.mp3" in our computer is played upon executing this application.

 
  1. package application;  
  2. import java.io.File;  
  3.   
  4. import javafx.application.Application;  
  5. import javafx.scene.Group;  
  6. import javafx.scene.media.Media;  
  7. import javafx.scene.media.MediaPlayer;  
  8. import javafx.scene.media.MediaView;  
  9. import javafx.stage.Stage;  
  10. public class JavaFX_Media Example extends Application  
  11. {  
  12.   
  13.     @Override  
  14.     public void start (Stage primaryStage) throws Exception {  
  15.         // TODO Auto-generated method stub  
  16.         //Initialising path of the media file, replace this with your file path   
  17.         String path = "/home/hpnmaratt/Downloads/test.mp3";  
  18.           
  19.         //Instantiating Media class  
  20.         Media media = new Media(new File(path).toURI().toString());  
  21.           
  22.         //Instantiating MediaPlayer class   
  23.         MediaPlayer mediaPlayer = new MediaPlayer(media);  
  24.           
  25.         //by setting this property to true, the audio will be played   
  26.         mediaPlayer.setAutoPlay(true);  
  27.         primaryStage.setTitle("Playing Audio");  
  28.         primaryStage.show();  
  29.     }  
  30.     public static void main(String[] args) {  
  31.         launch(args);  
  32.     }  
  33.       
  34.