简体   繁体   中英

Multithreading only way to play background music in Java?

I have a game with game logic happening in the main. I just added sound playing as per documentation I found:

//////////////////////SOUND/////////////////////////
     SourceDataLine soundLine = null;
     int BUFFER_SIZE = 64*1024;  // 64 KB

      // Set up an audio input stream piped from the sound file.
      try {
         File soundFile = new File("tim ph3 samplepart1.wav");
         AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);
         AudioFormat audioFormat = audioInputStream.getFormat();
         DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
         soundLine = (SourceDataLine) AudioSystem.getLine(info);
         soundLine.open(audioFormat);
         soundLine.start();
         int nBytesRead = 0;
         byte[] sampledData = new byte[BUFFER_SIZE];
         while (nBytesRead != -1) {
            nBytesRead = audioInputStream.read(sampledData, 0, sampledData.length);
            if (nBytesRead >= 0) {
               // Writes audio data to the mixer via this source data line.
               soundLine.write(sampledData, 0, nBytesRead);
            }
         }
      } catch (UnsupportedAudioFileException ex) {
         ex.printStackTrace();
      } catch (IOException ex) {
         ex.printStackTrace();
      } catch (LineUnavailableException ex) {
         ex.printStackTrace();
      } finally {
         soundLine.drain();
         soundLine.close();
      }
     /////////////////////////////////////////////////////

It plays the file I specified out of the files in my project folder in Eclipse.

The problem? It blocks all game logic after it that appears in the main.

This makes sense - the program is sequential and until the ENTIRE song is done...I figure the game can't go on.

This obviously isn't going to work, and it appears I'm going to have to go to dreaded multithreading...BUT BEFORE I DO...I wonder...is there a Java library or some other clever solution to avoid multithreading in this case?

Yes, you need to use a separate thread. There's nothing to be afraid of. Multithreading in Java is a piece of cake. Look at the Concurrency packages.

http://docs.oracle.com/javase/tutorial/essential/concurrency/

Beware: knowing how to start a thread and knowing how to safely multithread your programs are 2 different things. For now, make sure you avoid touching the same music from multiple threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM