java - 音乐无法在应用程序中播放(javax.sound.sampled.Clip)

标签 java javasound

import javax.sound.sampled.*;
import java.io.File;
public class PlayAudio{
public static void main(String args[])throws Exception{

    File wavFile = new File("C:\\Users\\User\\Desktop\\Wate.wav");
    AudioInputStream ais = AudioSystem.getAudioInputStream(wavFile);
    Clip clip=AudioSystem.getClip();
    clip.open(ais);
    clip.start();
 }
}

我的问题是:为什么这个应用程序不播放音乐? (IDE是Eclipse)

最佳答案

问题是您的主应用程序线程在声音剪辑可以播放之前退出。您可以在 clip.start() 之后调用任意超时的 Thread.sleep,但最好创建一个专用的 Thread 来跟踪播放时的音频数据:

public class PlayAudio {

    AudioFormat audioFormat;
    AudioInputStream audioInputStream;
    SourceDataLine sourceDataLine;

    boolean stopPlayback = false;

    public void playAudio(File soundFile) throws UnsupportedAudioFileException,
            IOException, LineUnavailableException {
        audioInputStream = AudioSystem.getAudioInputStream(soundFile);
        audioFormat = audioInputStream.getFormat();
        DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
        sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
        new Thread(new PlayThread()).start();
    }

    public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        new PlayAudio().playAudio(new File("myclip.wav"));
    }

    class PlayThread implements Runnable {
        byte soundBuffer[] = new byte[10000];

        @Override
        public void run() {
            try {
                sourceDataLine.open(audioFormat);
                sourceDataLine.start();
                int cnt;
                while ((cnt = audioInputStream.read(soundBuffer, 0,
                        soundBuffer.length)) != -1 && stopPlayback == false) {
                    if (cnt > 1) {
                        sourceDataLine.write(soundBuffer, 0, cnt);
                    }
                }
                sourceDataLine.drain();
                sourceDataLine.close();
                stopPlayback = false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

关于java - 音乐无法在应用程序中播放(javax.sound.sampled.Clip),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14305712/

相关文章:

java - 添加定制程序类以删除条形图中的条形之间的空间

java - JPA:即使使用了 getter 方法,延迟加载也不会加载。希望如此?

java - 播放不同音高的正弦波

java - SourceDataLine 音频发出爆裂声

javax.sound.sampled.UnsupportedAudioFileException : could not get audio input stream from input file when loading wav file

java - Processing/java 中文本到语音的长音节

java - 硬件麦克风控制

java - 应该检索公共(public)FTPClient的文件从远程服务器删除文件

对象、数组和原始类型的 Java 和精确引用大小

Java - 在构造函数方法调用中阻塞