gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:06:08 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com