我正在研究一種將wav文件修剪成由用戶進行的選擇的方法。基本思想是使用Javazoom的WaveFile
類來編寫一個wav文件,該文件僅包含用戶所做選擇中的聲音數據。問題是,我編寫的代碼完美地工作大約一半的時間,另一半時間它產生靜態。它似乎工作,並不在相同的情況下工作。 wav文件在另一個時間被MediaPlayer
加載,並作爲其他方法的輸入流。這是問題的可能來源嗎?我試圖小心關閉流並釋放MediaPlayer
,但仍然存在相同的問題。使用Javazoom修剪wav文件的方法有時可以運行
public void TrimToSelection(double startTime, double endTime){ // Time in seconds
InputStream wavStream = null; // InputStream to stream the wav to trim
File trimmedSample = null; // File to contain the trimmed down sample
File sampleFile = new File(samplePath); // File pointer to the current wav sample
// If the sample file exists, try to trim it
if (sampleFile.isFile()){
trimmedSample = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), "trimmedSample.wav");
if (trimmedSample.isFile()) trimmedSample.delete(); // Delete if already exists
// Trim the sample down and write it to file
try {
wavStream = new BufferedInputStream(new FileInputStream(sampleFile));
// Javazoom class WaveFile is used to write the wav
WaveFile waveFile = new WaveFile();
waveFile.OpenForWrite(trimmedSample.getAbsolutePath(), (int)audioFormat.getSampleRate(), (short)audioFormat.getSampleSizeInBits(), (short)audioFormat.getChannels());
// The number of bytes of wav data to trim off the beginning
long startOffset = (long)(startTime * audioFormat.getSampleSizeInBits() * audioFormat.getSampleRate()/4);
// The number of bytes to copy
long length = (long)(endTime * audioFormat.getSampleSizeInBits() * audioFormat.getSampleRate()/4) - startOffset;
wavStream.skip(44); // Skip the header
wavStream.skip(startOffset);
byte[] buffer = new byte[1024 * 16];
int bufferLength;
for (long i = startOffset; i < length + startOffset; i += buffer.length){
bufferLength = wavStream.read(buffer);
short[] shorts = new short[buffer.length/2];
ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);
waveFile.WriteData(shorts, shorts.length);
}
waveFile.Close(); // Complete writing the wave file
wavStream.close(); // Close the input stream
} catch (IOException e) {e.printStackTrace();}
finally {
try {if (wavStream != null) wavStream.close();} catch (IOException e){}
}
}
// Delete the original wav sample
sampleFile.delete();
// Copy the trimmed wav over to replace the sample
trimmedSample.renameTo(sampleFile);
}
更新:我改變long startOffset = (long)(startTime * audioFormat.getSampleSizeInBits() * audioFormat.getSampleRate()/4);
到long startOffset = ((long)startTime * audioFormat.getSampleSizeInBits() * (long)audioFormat.getSampleRate()/4);
同樣地,對於length
。出於某種原因改變演員陣容似乎已經解決了靜態問題(我認爲),儘管我不知道爲什麼。現在,我認爲我需要調整緩衝區循環,因爲樣本的末端被切斷。
謝謝,這絕對有幫助。它使用基本上與我相同的方法完成修剪wav文件。我可能已經解決了我的代碼中的主要問題,但我不知道爲什麼。在原文中查看我的編輯。 – 2014-10-08 02:38:01