0
我願意使用javax.sound API註冊來自麥克風的一些音頻,但生成的文件無法被我的音頻播放器讀取。嘗試使用javax.sound註冊語音
我寫了一個測試方法,開始一個線程註冊,等待幾秒鐘,通知中斷註冊,等待幾秒鐘,然後將錄製的音頻持久化到磁盤。
下面是代碼(不包括例外管理)。
public void record() {
VoiceRecorder voiceRecorder = new VoiceRecorder();
Future<ByteArrayOutputStream> result = executor.submit(voiceRecorder);
Thread.sleep(3000);
voiceRecorder.signalStopRecording();
Thread.sleep(1000);
ByteArrayOutputStream audio = result.get();
FileOutputStream stream = new FileOutputStream("./" + filename + ".mp3");
stream.write(audio.toByteArray());
stream.close();
}
VoiceRecorder是一類礦井,其核心代碼是這樣的:
public ByteArrayOutputStream call() {
AudioFormat standardFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 128, 16, 1, 2, 128, false);
TargetDataLine microphone = null;
microphone = AudioSystem.getTargetDataLine(format);
microphone.open(format);
int numBytesRead;
byte[] data = new byte[microphone.getBufferSize()/5];
// Begin audio capture.
microphone.start();
ByteArrayOutputStream recordedAudioRawData = new ByteArrayOutputStream();
while (!stopped) {
// Read the next chunk of data from the TargetDataLine.
numBytesRead = microphone.read(data, 0, data.length);
// Save this chunk of data.
recordedAudioRawData.write(data, 0, numBytesRead);
}
return recordedAudioRawData;
}
此代碼是由我的遺囑執行人運行和登記情況,其實會產生一個非空文件(684個字節持續3秒,988字節持續4秒),但它不會與我的玩家打開(如VLC)。
我應該在哪裏尋找問題?有沒有其他方法可以推薦您使用這種方法?下一步將是重現錄製的音頻。謝謝。
看起來您只是將您讀取的原始PCM字節寫入文件,這不是大多數玩家都知道如何處理的格式。您需要使用類似'AudioSystem.write'的文件以可識別的格式寫入文件。 –
可能是我的問題。這足以將AudioFormat更改爲新的AudioFormat(16000,8,2,true,true)並將文件保存爲Wav:AudioSystem.write(audioInputStream,AudioFileFormat.Type.WAVE,audioFile); – Manu
@ greg-449請您將評論移至回答,以便我可以接受它? – Manu