【问题标题】:AudioSystem clip doesn't stop playing when clip.stop(); is run当 clip.stop(); 时 AudioSystem 剪辑不会停止播放正在运行
【发布时间】:2014-01-22 13:19:35
【问题描述】:

我需要制作一个音频播放器,在运行此子程序时播放声音片段。它还必须在播放新的声音片段之前停止之前的声音片段。

我遇到的问题是剪辑从未注册为正在运行。检查它是否正在运行的两个 if 语句都没有使用过。这意味着剪辑仅在完成后停止,并且它们可能重叠并破坏程序。

我会使用 clip.stop();在其他子程序中,但它会告诉我找不到“剪辑”符号。我不知道如何使它可供其他子例程使用。

我可以获得 clip.stop(); 的唯一方法;在这个子例程中工作是把它直接放在clip.start()之后;线,在开始后立即停止剪辑,因此根本听不到。

下面是我用来播放音频片段的子程序。

public void play(String filename){
    try {
        Clip clip = AudioSystem.getClip();
        audFile = audDir + filename;
        if (clip.isRunning()){
            System.out.println("Sounds playing 1");
            clip.stop();
        }
        clip.open(AudioSystem.getAudioInputStream(new File(audFile)));
        clip.start();
        if (clip.isRunning()){
            System.out.println("Sounds playing 2");
            clip.stop();
        }
    } catch (Exception exc) {
        exc.printStackTrace(System.out);
    }
}

【问题讨论】:

  • 看看这里,也许对你有帮助或者给你一个解决方案:stackoverflow.com/questions/5833553/…
  • I would use clip.stop(); in other subroutines, but it will tell me that the 'clip' symbol cannot be found. 这是否意味着您的代码会给您带来错误?如果有,具体在哪里?

标签: java audio clip


【解决方案1】:

我会使用 clip.stop();在其他子程序中,但它会告诉我 找不到“剪辑”符号。我不知道怎么做 可供其他子程序使用。

在你的类中声明一个私有的 Clip 字段

private Clip clip;

当你从AudioSystem.getClip()得到它时设置它。

/*
 * clip (local variable) is invisible from other methods
 */
Clip clip = AudioSystem.getClip(); 
this.clip = clip; // `this.clip` is a field, it's visible from other methods

然后您可以从其他方法访问它(“子例程”是 Java 中的类方法)。

我遇到的问题是剪辑从未注册为正在运行。

当你调用clip.isRunning()时它没有运行,但你确定它从不运行吗?

您不能假设clip.isRunning()clip.start() 之后立即返回true。该机制是异步的,注册LineListener 并监听START 事件可能会有所帮助。

clip.start();
LineListener listener = new LineListener() {
    public void update(LineEvent event) {
    if (event.getType() == LineEvent.Type.START) {
            /*
             * here you are sure the clip is started
             */
        }
    }
};
clip.addLineListener(listener );

【讨论】:

  • 我还是一头雾水。我会使用this.clip.start(); / this.clip.stop(); 以及Clip clip = AudioSystem.getClip();this.clip = clip; 之类的东西吗?
  • 是的,你会的。 (顺便说一句,你不需要拼写this.clip.start()this.clip.stop(),只需clip.start()clip.stop() 即可)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多