multithreading - Looping audio on separate thread in Java -


I'm making a 2D RPG game and I wanted to do background music work. I wrote a sound class that plays music on a different thread but I can not understand how to make a loop in my voice class:

  Package tile RPG.gfx; Import java.io.file; Import java.io.IOException; Import javax.sound.sampled.AudioFormat; Import javax.sound.sampled.AudioInputStream; Import javax.sound.sampled.Audio system; Import javax.sound.sampled.DataLine; Import javax.sound.sampled.LineUnavailableException; Import javax.sound.sampled.SourceDataLine; Public class sound tools runner {personal string file location = "res / bgMusic.wav"; Public Sound () {} Public Zero Games () {Thread T = New Thread (This); T.start (); } Public Zero Run () {playSound (fileLocation); } Private Zero place (string filename) {file sound file = new file (filename); Audioindstream audioInputTream = faucet; Try {audioInputStream = AudioSystem.getAudioInputStream (soundFile); } Hold (exception e) {e.printStackTrace (); } AudioFormat AudioFormat = AudioInputStream.Getformat (); Source data line line = zero; DataLine.Info Info = New DataLine.Info (SourceDataLine.class, audioFormat); Try {line = (SourceDataLine) AudioSystem.getLine (info); Line.open (audioFormat); } Hold (LineUnavailableException E) {e.printStackTrace (); } Hold (exception e) {e.printStackTrace (); } Line. Start (); Int nBytesRead = 0; Byte [] abData = new byte [128000]; While (nBytesRead! = -1) {try {nBytesRead = audioInputStream.read (abData, 0, abData.length); } Hold (IOException e) {e.printStackTrace (); } If (nBytesRead> = 0) {int nBytesWritten = line.write (abData, 0, nBytesRead); }} Line.drain (); Line.close (); }}    

  goes public zero () {while (true) {playSound (file location); }}   

This creates an infinite loop. Adjust accordingly.

When you start a thread, it will execute any code that is in the run () method and then exit, this is where the loop is bar- Bands play sound (without blocking their other threads / codes)

This solution has no way to stop this thread (and therefore, preventing playback), but I believe that you are writing it in phases. This thread will stop playback and when the application is running.

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -