简体   繁体   English

尝试将原始PCM写入WAV并且仅获取标头

[英]Trying to write raw PCM to WAV and only getting header

I am currently using this code: 我目前正在使用此代码:

File wavFile=new File("tmp"+File.separator+"recordings"+File.separator+uuid.toString()+".wav");
try{
    FileInputStream pcmInputStream=new FileInputStream(file);
    FileOutputStream wavOutputStream=new FileOutputStream(wavFile);
    AudioSystem.write(new AudioInputStream(new ByteArrayInputStream(IOUtils.toByteArray(pcmInputStream)),
    new AudioFormat(48000,16,2,true,
    true),IOUtils.toByteArray(pcmInputStream).length/4),
    AudioFileFormat.Type.WAVE,wavOutputStream);
    wavOutputStream.flush();
    wavOutputStream.close();
    pcmInputStream.close();
    fileOutputStream.close();
}catch(IOException e){
    e.printStackTrace();
}

Having checked, I can confirm that the PCM has 30 seconds of data and is approximately 4.7MB. 检查后,我可以确认PCM具有30秒的数据,大约为4.7MB。 This writes the .wav file however it is only 44 bytes and not playable, I reckon that this 44 bytes is the RIFF header but am unsure of how to solve it. 这将写入.wav文件,但是它只有44个字节且无法播放,我认为这44个字节是RIFF标头,但不确定如何解决。 I have tried using different lengths and different combinations of File/ByteArray OutputStreams. 我尝试使用不同的长度和File / ByteArray OutputStreams的不同组合。

When creating the AudioInputStream , you call IOUtils.toByteArray(pcmInputStream) twice, and on the second call, the input stream is already advanced to the end, so toByteArray returns an empty array. 创建AudioInputStream ,您两次调用IOUtils.toByteArray(pcmInputStream) ,并且在第二次调用时,输入流已经前进到末尾,因此toByteArray返回一个空数组。 This results in 0 getting passed as the argument to the AudioInputStream constructor's length. 这导致将0作为参数传递给AudioInputStream构造函数的长度。

new AudioInputStream(
    new ByteArrayInputStream( IOUtils.toByteArray(pcmInputStream) ),
    new AudioFormat(48000,16,2,true,true),
    ( IOUtils.toByteArray(pcmInputStream) ).length/4
)

You should save the byte array to a temporary variable instead of trying to call toByteArray twice on the same input stream. 您应该将字节数组保存到一个临时变量,而不是尝试在同一输入流上两次调用toByteArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM