2013-06-12 59 views
1

我想将字节数组转换为AudioInputStream。字节数组之前是从* .wav文件填充的。我有以下代码:如何将字节数组转换为Java中的AudioInputStream

public static AudioInputStream writeBytesBackToStream(byte[] bytes) { 
    ByteArrayInputStream baiut = new ByteArrayInputStream(bytes); 
    AudioInputStream stream = null; 
    try { 
     stream = AudioSystem.getAudioInputStream(baiut); 
    } catch (UnsupportedAudioFileException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    if(stream.equals(null) || stream == null) { 
     System.out.println("WARNING: Stream read by byte array is null!"); 
    } 
    return stream; 
} 

现在我只希望这个字节数组转换成的AudioInputStream,而是UnsupportedAudioFileException抛出:

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream 

有没有人有一个想法?

+0

使用[这](http://docs.oracle.com/javase/1.5.0/docs/ api/javax/sound/sampled/AudioSystem.html#isFileTypeSupported(javax.sound.sampled.AudioFileFormat.Type))来确认它支持wav文件,并且测试将wav文件传递给getAudioInputStream ...因此您可以检查如果问题出在bytearray或文件itseld – fmodos

+0

你可以发布wav文件加载代码来检查你的字节数组是否正确? – gma

+0

我相信Durandel的答案是正确的,但阅读这本入门书可能会有所帮助:http://blog.bjornroche.com/2013/05/the-abcs-of-pcm-uncompressed-digital.html –

回答

1

如果您正确读取WAV文件,则字节数组将只包含原始PCM数据。因此,AudioSystem无法识别流的格式并抛出异常。

这不能通过设计工作。您需要在流中提供完整的音频格式图像,以使AudioSystem识别流的格式,而不仅仅是原始数据。

+0

谢谢你,写一个.wav标题是解决方案。我认为即使没有标题,也可以随时获得AudioInputStream。 –

+0

@Kosch如果你对此有所了解,那将无法实现。 getAudioInputStream()如何确定其单声道/立体声,每个采样的字节数,字节顺序和来自原始数据的采样率? – Durandal

2

如果数据实际上是PCM,另一种方法是手动设置AudioFormat参数。以下是创建A未成年人的示例。

byte[] b = new byte[64000]; 
    //lets make a 440hz tone for 1s at 32kbps, and 523.25hz. 
    for(int i = 0; i<b.length/2; i++){ 

     b[i*2+1] = (byte)(127*Math.sin(4*Math.PI*440.0/b.length*i)); 
     b[i*2] = (byte)(127*Math.sin(4*Math.PI*523.25/b.length*i)); 
    } 

    AudioInputStream stream = new AudioInputStream(
     new ByteArrayInputStream(b), 
     new AudioFormat(16000, 8, 2, true, false), 
     64000 
    ); 

此外,如果你正在做字节转换成声音要小心,你有耳机英寸

相关问题