![](/img/trans.png)
[英]How is it possible to navigate to wav.file in src (for playing sound in java)
[英]playing wav file in java - how do I extend or concatenate the sound played?
是否可以創建一個包含 wav 文件“循環”的臨時文件?
或者是否可以操作發送到 stream 讀/寫器的 stream?
基本上我想播放一些 wav 文件一段時間,如果該時間大於 wav 文件提供的時間長度,我想循環播放。
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.loop((int)(Math.ceil(timeRequested / audioIn.getFrameLength())));
我不確定我是否理解您實施解決方案的確切限制,但似乎最干凈的方法是在您第一次播放文件時將音頻數據存儲在緩沖區中。 然后,如果用戶需要更多迭代(全部或部分),只需將緩存的數據重寫回 SourceDataLine 所需的次數。
這是一個示例聲音文件播放器 (PCM) 的鏈接,它的代碼應該很容易修改(或只是從中學習)。 我還破解了一些(注意:未經測試)代碼,這些代碼僅顯示了我上面描述的邏輯:(您可能還想修改我在下面的內容以符合有關僅寫入大小為倍數的數據塊的規則幀大小。)
public void playSoundFile(SourceDataLine line, InputStream inputStream, AudioFormat format, long length, float times)
{
int index = 0;
int size = length * format.getFrameSize();
int currentSize = 0;
byte[] buffer = new byte[size];
AudioInputStream audioInputStream = new AudioInputStream(inputStream, format, length);
while (index < size)
{
currentSize = audioInputStream.read(buffer, index, size - index);
line.write(buffer, index, currentSize);
index += currentSize;
}
float currentTimes = 1.0;
while (currentTimes < times)
{
float timesLeft = times - currentTimes;
int writeBlockSize = line.available();
index = 0;
if (timesLeft >= 1.0)
{
while (index < size)
{
currentSize = ((size - index) < writeBlockSize) ? size - index : writeBlockSize;
line.write(buffer, index, currentSize);
index += currentSize;
}
currentTimes += 1.0;
}
else
{
int partialSize = (int)(timesLeft * ((float) size) + 0.5f);
while (index < partialSize)
{
currentSize = ((partialSize - index) < writeBlockSize) ? partialSize - index : writeBlockSize;
line.write(buffer, index, currentSize);
index += currentSize;
}
currentTimes += timesLeft;
}
}
}
希望有幫助!
我想我將使用音頻輸入 stream 中的每秒幀數和幀大小信息來解決這個問題。 其他有用的信息在 SourceDataLine object 的 getMicrosecondPosition() 方法中,以確定到目前為止播放的時間/持續時間。
這與音頻輸入 stream 中的標記和重置方法一起可能會解決所有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.