banner



How To Play A Music File In The Background Java

Play Sound in Coffee

  1. Play Audio Using Prune in Java
  2. Play Sound Using SourceDataLine in Java

Java applications will sometimes be required to play audio files. Given that sound is fourth dimension-based information and must be delivered at the correct rate for it to be rendered for the user'due south perception. An altercation of the charge per unit at which data is delivered will misconstrue the audio beingness played. Java Audio API's objective is to ensure that sound data is delivered at the correct rate and continuously over when the sound is being played. It achieves this by playing sound through a line to ensure it remains smooth and consequent. The ii kinds of lines that Java provides are Prune and SourceDataLine.

The difference betwixt the ii is in the approach of specifying the sound data. With Clip, all the sound data is specified once before the playback procedure, while in SourceDataLine, in that location is continuous buffer writing throughout the playback process. These two methods just support sound files in the following formats: AIFF, AIFC, WAVE, AU, and SND. There are many scenarios where a developer tin can utilize either of the ii and await to become the aforementioned upshot, but in that location are also scenarios where i gives improve results than the other. Beneath is an explanation on how to choose the virtually effective line for your application's needs.

  1. Clip

It is more constructive when you lot want to read and play a brusque sound file as a clip more than one fourth dimension. The Prune'due south full functionality strength is best experienced when the user wants to loop the audio beingness played. This feature likewise allows the user to select the place where they want to start playback randomly. The clip is faster because the sound file is loaded and thus doesn't require more buffering after being looped or after the user selects to motion to a random file position.

  1. SourceDataLine

This is more effective when a user wants to optimize the memory while playing a large sound file. It is besides the best choice when the developer doesn't know the sound that will exist played. This method is also more effective when there is a demand for sound transformation because information technology requires the sound data to be continuously updated by the application during playback.

Play Sound Using Prune in Java

The clip is available in javax.sound.sampled bundle and was introduced in Java 7.

In this case, we shall cover start, pause, resume, stop, restart and start at a random position.

Below are the steps involved:

  • The first footstep is to create an object of the sound input stream. This step converts the audio file into an input stream that the app can use.
  • The 2nd step is to use Audio System to create an object for clip reference
  • The third step is now to load the clip object with audio data from the sound input stream that was created in step 1.
  • The next step is to set the clip'due south required properties such as loop, position, and microsecond position
  • You can then kickoff the clip.
              import coffee.io.File;  import coffee.util.Scanner;  import coffee.io.IOException;   import javax.sound.sampled.AudioSystem;  import javax.sound.sampled.AudioInputStream;  import javax.audio.sampled.LineUnavailableException; import javax.audio.sampled.Clip;   import javax.sound.sampled.UnsupportedAudioFileException;   public class SoundPlayer  {   	//define storage for start position 	Long nowFrame;  	Clip clip;  	 	// get the prune status  	String thestatus;  	 	AudioInputStream audioStream;  	static String thePath;   	// initialize both the prune and streams  	public SoundPlayer()  		throws UnsupportedAudioFileException,  		IOException, LineUnavailableException  	{  		// the input stream object  		audioStream =  				AudioSystem.getAudioInputStream( 				    new File(thePath) 				    .getAbsoluteFile());  		 		// the reference to the clip  		clip = AudioSystem.getClip();    		clip.open(audioStream);  		 		clip.loop(Clip.LOOP_CONTINUOUSLY);  	}   	public static void main(String[] args)  	{  		try 		{  		  //add the path to the audio file 			thePath = "add the path to the audio file here";  		 			SoundPlayer simpleSoundPlayer =  							new SoundPlayer();  			 			simpleSoundPlayer.play();  			Scanner scanned = new Scanner(Organisation.in);  			 			//show the options 			while (true)  			{  				System.out.println("1. suspension");  				System.out.println("2. resume");  				Arrangement.out.println("3. restart");  				System.out.println("4. stop");  				System.out.println("5. Jump to specific time");  				int a = scanned.nextInt();  				simpleSoundPlayer.gotoChoice(a);  				if (a == 4)  				intermission;  			}  			scanned.close();  		}  		 		catch (Exception east)  		{  			Organisation.out.println("Experienced an error while playing sound.");  			e.printStackTrace();  		 		}  	}  	 	// operation is now every bit per the user'southward selection  	 	private void gotoChoice(int a)  			throws IOException, LineUnavailableException, UnsupportedAudioFileException  	{  		switch (a)  		{  			instance 1:  				break();  				break;  			case 2:  				resumeAudio();  				break;  			case 3:  				restart();  				break;  			case 4:  				end();  				break;  			case 5:  				System.out.println("Selected time (" + 0 +  				", " + clip.getMicrosecondLength() + ")");  				Scanner browse = new Scanner(Organisation.in);  				long cc = scan.nextLong();  				leap(cc);  				break;  	 		}  	 	}  	 	// play  	public void play()  	{  		//start the clip  		clip.start();  		 		thestatus = "play";  	}  	 	// Pause audio  	public void interruption()  	{  		if (thestatus.equals("paused"))  		{  			System.out.println("audio is already paused");  			return;  		}  		this.nowFrame =  		this.clip.getMicrosecondPosition();  		clip.cease();  		thestatus = "paused";  	}  	 	// resume audio 	public void resumeAudio() throws UnsupportedAudioFileException,  							IOException, LineUnavailableException  	{  		if (thestatus.equals("play"))  		{  			Organization.out.println("The audio is"+  			"being played");  			render;  		}  		clip.close();  		resetAudioStream();  		prune.setMicrosecondPosition(nowFrame);  		this.play();  	}  	 	// restart audio  	public void restart() throws IOException, LineUnavailableException,  											UnsupportedAudioFileException  	{  		clip.end();  		clip.close();  		resetAudioStream();  		nowFrame = 0L;  		clip.setMicrosecondPosition(0);  		this.play();  	}  	 	// finish audio  	public void stop() throws UnsupportedAudioFileException,  	IOException, LineUnavailableException  	{  		nowFrame = 0L;  		prune.terminate();  		clip.close();  	}  	 	// spring to a selected bespeak  	public void jump(long a) throws UnsupportedAudioFileException, IOException,  														LineUnavailableException  	{  		if (a > 0 && a < clip.getMicrosecondLength())  		{  			clip.stop();  			clip.close();  			resetAudioStream();  			nowFrame = a;  			clip.setMicrosecondPosition(a);  			this.play();  		}  	}  	 	// reset the audio stream  	public void resetAudioStream() throws UnsupportedAudioFileException, IOException,  											LineUnavailableException  	{  		audioStream = AudioSystem.getAudioInputStream(  		new File(thePath).getAbsoluteFile());  		clip.open(audioStream);  		clip.loop(Clip.LOOP_CONTINUOUSLY);  	}   }                          

This programme uses an audio stream obtained from the sound data using the AudioInputStream. This must exist the first footstep because the program simply recognizes the data as a stream which has to exist reset if it is to be reused.

Operations Caption

Pause: To successfully break the player, the electric current frame must be stored in an object after the thespian stops. The frame is stored to ensure that the actor can resume when the resume method is called. Pause method uses the clip.getMicrosecondPosition() to capture the suspension point.

Resume: When the resume method is chosen, it uses the frame stored in an object to know where to continue from. Resume uses the prune.setMicrosecondPosition(nowFrame) to reset the sound stream to the position information technology was at when the pause method was called.

End: The stop method closes and stops the clip. When this method is called, the user cannot resume their position before because the frame was not stored. This is the technical difference between suspension and stop.

It is always advisable that before endmost the plan, the open up streams should be closed. While using the above programs, proper checks are implemented by stopping the clip before playing information technology again. This ensures that the sound remains consequent and the resources are efficiently utilized while playback is ongoing. As a dominion in Java, a stream, in this case, the audio stream cannot be reused earlier being reset. Failure to reset information technology earlier reusing it volition atomic number 82 to the program giving an error.

Play Sound Using SourceDataLine in Java

The SourceDataLine is found in javax.audio.sampled.SourceDataLine. To implement SourceDataLine sound play, we follow the following steps.

  • The first footstep is to create an object of the sound input stream. This stride converts the audio file into an input stream that the app tin can utilise.
  • The second footstep is to open a line using the AudioSystem.getLine() method.
  • The third stride is to repeatedly read the specified chunks of the audio input stream created in stride 1 and forward it to SourceDataLine's buffer. This is repeated until the end of the audio stream.
  • Later on the read and buffer have been completed, the resources are freed by closing the line.
              import java.io.File; import java.io.IOException;   import javax.audio.sampled.AudioInputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.sound.sampled.SourceDataLine;   public class simpleSoundPlayer {       //defining the byte buffer     private static last int BUFFER_SIZE = 4096;            void play(String filePath) {         File soundFile = new File(filePath);         effort {           //convering the audio file to a stream             AudioInputStream sampleStream = AudioSystem.getAudioInputStream(soundFile);               AudioFormat formatAudio = sampleStream.getFormat();               DataLine.Info info = new DataLine.Info(SourceDataLine.class, formatAudio);               SourceDataLine theAudioLine = (SourceDataLine) AudioSystem.getLine(info);               theAudioLine.open(formatAudio);               theAudioLine.kickoff();                           System.out.println("Sound Player Started.");                           byte[] bufferBytes = new byte[BUFFER_SIZE];             int readBytes = -1;               while ((readBytes = sampleStream.read(bufferBytes)) != -i) {                 theAudioLine.write(bufferBytes, 0, readBytes);             }                           theAudioLine.drain();             theAudioLine.close();             sampleStream.close();                           Organization.out.println("Playback has been finished.");                       } catch (UnsupportedAudioFileException e) {             System.out.println("Unsupported file.");             e.printStackTrace();         } catch (LineUnavailableException due east) {             System.out.println("Line not establish.");             e.printStackTrace();         } catch (IOException eastward) {             System.out.println("Experienced an error.");             e.printStackTrace();         }           }           public static void principal(String[] args) {         Cord thePath = "path to your audio file here";         simpleSoundPlayer player = new simpleSoundPlayer();         role player.play(thePath);     }   }                          

The program higher up is most constructive when the user wants to read a big file without giving upwards a lot of memory infinite. This can too be applied when the user is streaming real-fourth dimension sound information and does non want to take unnecessary lag-fourth dimension. When well implemented, this method of playing sound can lead to a user getting smooth and consistent sound with very low memory usage. Withal, failure to close the line can lead to memory bottleneck and, ultimately, sound distortion.

SoundDataLine is limited in the following ways:

  1. A user can't start playing from an arbitrary position
  2. Information technology is not possible to loop the sound
  3. Information technology is not possible to pause and resume as you would with a clip
  4. A user cannot know the duration of the selected audio file before they play it

This limits the scenarios where a user can effectively benefit from the SoundDataLine plan to large files or online streaming services.

Write for united states of america

DelftStack manufactures are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for united states page.

Ezoic

How To Play A Music File In The Background Java,

Source: https://www.delftstack.com/howto/java/play-sound-in-java/

Posted by: rathcatill.blogspot.com

0 Response to "How To Play A Music File In The Background Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel