java - 在java中播放声音

标签 java audio javasound

我有五个 wav 文件。我想使用 sourceDataLine 从单个 Java 程序连续播放它们。但我的程序没有保持正确的顺序。谁能给我提供代码段吗?

最佳答案

您检查过Documentation吗? ?

试试 here 中的这个例子:

import java.io.*;
import javax.sound.sampled.*;
/**
 * Use SourceDataLine to read line-by-line from the external sound file.     
 */
public class SoundLineTest {
   public static void main(String[] args) {
      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("gameover.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();
      }
   }
}

关于java - 在java中播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8921318/

相关文章:

java - 在 JPA (EclipseLink) 上映射 Oracle XMLType

java - 如何在 Eclipse IDE 中使用 SVN 部署 Java 项目?

java - 使用字节数组创建 AudioInputStream

java - 来自 Java UDP 的空指针异常

java - GC 调优 - 防止 Full GC

xcode - 声音文件完成之前,Xcode屏幕不会更新

ios - OpenAL 随机停止播放某些声音,只能通过重启来修复

android - Ubuntu 中的 C/C++ 套接字,用于从 Android 麦克风输入接收音频流

java - SourceDataLine.start() 将对象清空

java - 只能第一次从 TargetDataLine 记录