简体   繁体   English

在java中播放音频文件

[英]Playing an audio file in java

My goal is to make a program that displays a pop up window with a single button called play . 我的目标是创建一个程序,显示一个弹出窗口,其中包含一个名为play按钮。 I am using an inner class and action listener. 我正在使用内部类和动作侦听器。 The button does in fact play the audio clip. 该按钮实际上播放音频剪辑。 Now what I would like to do is make it so every time I hit the play button it plays it from the beginning and I do not hear more than one instance of the clip being played in it's completion. 现在我想做的就是这样做,每当我点击播放按钮时它就从头开始播放,我听不到在它完成时播放的片段的多个实例。 Here is the code I have for the inner class only: 这是我对内部类的代码:

private class PlaySound implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        String filename = "/Users/philipgouldman/Desktop/iPhoneRingtones/Dummy_Yeah.wav";

        try {
            Clip clip = AudioSystem.getClip();
            clip.open(AudioSystem.getAudioInputStream(new File(filename)));
            clip.setFramePosition(0);
            clip.start();
        } catch (Exception exc) {
            exc.printStackTrace(System.out);
        }
    }

}

I would appreciate any tips or suggestions to achieve this goal. 我希望有任何提示或建议来实现这一目标。 I read on the Clip Interface javadoc that if the user wants the action to restart to simply invoke stop following setFramePosition(0) . 我在Clip接口javadoc上读到,如果用户想要重启动作,只需在setFramePosition(0)之后调用stop I can't say I quite understand what that means. 我不能说我完全明白这意味着什么。 Can someone guide me in the right direction? 有人能引导我朝正确的方向发展吗?

Move your Clip Object outside of this handle so that its state can be investigated later. Clip对象移动到此句柄之外,以便稍后可以调查其状态。

eg 例如

private class PlaySound implements ActionListener {

    private Clip clip = null;
    public void actionPerformed(ActionEvent e) {
        String filename = "/Users/philipgouldman/Desktop/iPhoneRingtones/Dummy_Yeah.wav";

        try {
            if (clip == null) {
                clip = AudioSystem.getClip();
                clip.open(AudioSystem.getAudioInputStream(new File(filename)));
            }
            clip.setFramePosition(0);
            clip.start();
        } catch (Exception exc) {
            exc.printStackTrace(System.out);
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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