java - 当 clip.stop(); 时,AudioSystem 剪辑不会停止播放;正在运行

标签 java audio clip

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

我遇到的问题是剪辑从未注册为正在运行。检查它是否正在运行的两个 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);
    }
}

最佳答案

I would use clip.stop(); in other subroutines, but it will tell me that the 'clip' symbol cannot be found. I don't know how to make it available for other subroutines to use.

在你的类中声明一个私有(private)的 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 中的类方法)。

The issue I'm having is that the clip is never registered as running.

当您调用 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 );

关于java - 当 clip.stop(); 时,AudioSystem 剪辑不会停止播放;正在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21284062/

相关文章:

java - 反序列化异常后继续在reactor kafka中消费后续记录

http - 从 mp3/ogg 中删除精确的时间范围

ios - FFmpeg 的音频替代品 - Core Audio IOS

c++ - OpenGL 近平面剪裁太多

java - 如何在连续按下 JButton 的同时使用 Clip 更流畅地播放音频文件

java - 使用 selenium 在 bigbasket 的购物车中搜索并添加产品

java - 在 Java 中使用 && 和相同的变量分配给一个变量是否正确?

java - 通过 JTDS 驱动程序执行 SQL Server 调用时出现 "Invalid JDBC escape syntax at line position 24 ' =' character expected"错误的原因?

python - 如何在 python 和 ffmpeg 或类似中读取实时麦克风音量

css - 如何水平裁剪文本?