java - 我如何停止播放声音? -Java

标签 java audio

这是我用来播放声音的代码,它非常适合我的需求。我只是不知道如何在需要时停止播放剪辑。

public class Sound {

    public Clip play(String filename) {
        Clip clip = null;

            try {
                File file = new File(filename);
                AudioInputStream audioIn = AudioSystem.getAudioInputStream(file);
                clip = AudioSystem.getClip();
                clip.open(audioIn);
                clip.stop();
                clip.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return clip;
       }
}

最佳答案

如果您查看 JavaDocs Clip您应该注意,从 DataLine 继承的方法之一是 stop

Stops the line. A stopped line should cease I/O activity. If the line is open and running, however, it should retain the resources required to resume activity. A stopped line should retain any audio data in its buffer instead of discarding it, so that upon resumption the I/O can continue where it left off, if possible. (This doesn't guarantee that there will never be discontinuities beyond the current buffer, of course; if the stopped condition continues for too long, input or output samples might be dropped.) If desired, the retained data can be discarded by invoking the flush method. When audio capture or playback stops, a STOP event is generated.

您可能需要验证这一点,但我似乎理解 start 是一个阻塞方法,也就是说,一旦调用,直到 Clip 完成才会返回玩。这需要在单独的线程中启动Clip

关于java - 我如何停止播放声音? -Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22701280/

相关文章:

java - 当 TextView getLineCount 包含 "\n"时返回错误的数字

ios - 应用程序运行时无法将蓝牙耳机与AVAudioSessionCategoryPlayAndRecord连接

Python:从 Python 中的 wav 文件计算随时间变化的频率?

java - 缓解警告消息 "References to generic type Iterator<E> should be parameterized"?

java - 分配的元空间大于 MaxMetaspaceSize

java - 在 Docker-Java API 中构建图像/容器时如何连接到自定义网络

c# - 如何在C#.net中以.avi扩展名添加视频声音

javascript - 如何显示自定义音频播放器的当前时间和总时长?

php - 使用 PHP shell_exec 和 ffmpeg 合并 2 个音频文件

java.sql.SQLException : column id is not unique