简体   繁体   English

如何在Java中将字节数组转换为AudioInputStream

[英]How to convert a byte array into an AudioInputStream in Java

I want to convert a byte array into an AudioInputStream. 我想将字节数组转换为AudioInputStream。 The byte array was filled from a *.wav file before. 字节数组之前是从* .wav文件填充的。 I have the following code: 我有以下代码:

    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;
}

Now I only want to convert this byte array into an AudioInputStream, but an UnsupportedAudioFileException is thrown: 现在,我只想将此字节数组转换为AudioInputStream,但是会引发UnsupportedAudioFileException:

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

Has anyone got an idea? 有人知道吗?

Another way to do this, if the data is actually PCM, is to set the AudioFormat parameters manually. 如果数据实际上是PCM,则另一种方法是手动设置AudioFormat参数。 Here is an example to create an A minor. 这是创建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
    );

Also be careful if you're making bytes into sounds and you have earphones in. 如果要使字节变成声音并且有耳机,请当心。

If you properly read the WAV file, the byte array will just contain raw PCM data. 如果您正确读取WAV文件,则字节数组将仅包含原始PCM数据。 Consequently the AudioSystem can not identify the format of the stream and throws the exception. 因此,AudioSystem无法识别流的格式并引发异常。

This can not work by design. 这不能设计使然。 You need to provide a complete audio format image in your stream to have AudioSystem recognize what format the stream is, not just raw data. 您需要在流中提供完整的音频格式图像,以使AudioSystem识别流是什么格式,而不仅仅是原始数据。

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

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