重新启动 Clip 对象 - flush() 方法

Restarting a Clip object - flush() method

Javadoc for DataLine.flush()

Flushes queued data from the line. The flushed data is discarded. In some cases, not all queued data can be discarded. For example, a mixer can flush data from the buffer for a specific input line, but any unplayed data already in the output buffer (the result of the mix) will still be played. You can invoke this method after pausing a line (the normal case) if you want to skip the "stale" data when you restart playback or capture. (It is legal to flush a line that is not stopped, but doing so on an active line is likely to cause a discontinuity in the data, resulting in a perceptible click.)

这到底是什么意思?

此外,为了重新启动 Clip 对象,该站点上的许多人建议使用此方法:

clip.stop();
clip.setFramePosition(0);
clip.start();

当使用上面的代码时,我注意到一个示例剪辑(如果重要的话大约 15 秒长)不会在开头重新开始并且其 "restarting position." 不一致但是,当我尝试

clip.stop();
clip.flush();
clip.setFramePosition(0);
clip.start();

剪辑工作完美,并在声音开始时重新开始。我的问题是,flush() 方法做了什么来解决我之前的问题?另外,为什么我一开始就遇到了这个问题?

Clip这样的数据线有一个内部数据缓冲区,可能是byte[]。缓冲区通常会在播放位置之前以块的形式填充。

假设在某个时刻我们有:

            playback position
                   v
buffer:         [..|.....]
  file: [..........|.....................]

所以如果我们停止该行,缓冲区中仍然有数据——播放位置之前的数据。

如果我们只设置播放位置,数据还在,下次启动时会播放。刷新行会丢弃此数据。

我们也可以调用drain等待数据回放