如何修复此java代码以播放音频文件?

时间:2017-12-25 00:28:04

标签: java audio

我正在尝试学习如何播放音频文件并提出以下代码。没有错误,我放入.wav文件的路径,但声音文件不播放。我该如何解决这个问题?

    import java.io.File;
    import java.io.IOException;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.UnsupportedAudioFileException;

    public class RunPlayer {

        public void runner(String audioFilePath) throws UnsupportedAudioFileException, IOException, LineUnavailableException { 
            File audioFile = new File(audioFilePath);

            AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);

            AudioFormat format = audioStream.getFormat();

            DataLine.Info info = new DataLine.Info(Clip.class, format);

            Clip audioClip = (Clip) AudioSystem.getLine(info);

            audioClip.open(audioStream);
            audioClip.start();

            audioClip.close();
            audioStream.close();
        }

        public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
            RunPlayer run = new RunPlayer();
            run.runner("thefilepathIentered");
        }

   }

1 个答案:

答案 0 :(得分:0)

问题必定是您在开始剪辑后立即关闭audioClip和audioStream。

你想要剪辑运行,然后可能有某种按钮或功能,一旦完成播放就会关闭剪辑。

看一下这个答案:https://stackoverflow.com/a/11025384/815086