剪辑没有播放任何声音

0 java audio javasound

好吧,标题说明了所有,我尝试使用javax.sound播放一个wav文件,但没有任何事情发生.我试过很多不同的文件而没有任何运气.

public static void main(String[] args) throws IOException, UnsupportedAudioFileException, LineUnavailableException
{

    File in = new File("C:\\Users\\Sandra\\Desktop\\music\\rags.wav");
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
    Clip play = AudioSystem.getClip();
    play.open(audioInputStream);
    FloatControl volume= (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
    volume.setValue(1.0f); // Reduce volume by 10 decibels.
    play.start();

}
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 8

因为,已经开始声明,您需要阻止主线程退出,因为这将导致JVM终止.

Clip#start 不是阻塞调用,这意味着它会在调用之后(很快)返回.

我毫不怀疑有很多方法可以解决这个问题,这只是其中之一的一个简单例子.

public class PlayMusic {

    public static void main(String[] args) throws InterruptedException {
        Clip play = null;
        try {
            File in = new File("C:\\Users\\Public\\Music\\Sample Music\\Kalimba.wav");
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
            play = AudioSystem.getClip();
            play.open(audioInputStream);
            FloatControl volume = (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
            volume.setValue(1.0f); // Reduce volume by 10 decibels.
            play.start();
            // Loop until the Clip is not longer running.
            // We loop this way to allow the line to fill, otherwise isRunning will
            // return false
            //do {
            //    Thread.sleep(15);
            //} while (play.isRunning());
            play.drain();
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
            ex.printStackTrace();
        } finally {
            try {
                play.close();
            } catch (Exception exp) {
            }
        }
        System.out.println("...");
    }
}
Run Code Online (Sandbox Code Playgroud)

实际的解决方案将取决于您的需求.