有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

信号处理如何在Java中将字节数组转换为音频输入流

我想把字节数组转换成音频输入流。字节数组是从*填充的。之前的wav文件。我有以下代码:

    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

有人有主意吗


共 (2) 个答案

  1. # 1 楼答案

    如果数据实际上是PCM,另一种方法是手动设置AudioFormat参数。下面是一个创建小调的示例

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

    如果你正在将字节转换成声音,并且你有耳机,也要小心

  2. # 2 楼答案

    如果正确读取WAV文件,字节数组将只包含原始PCM数据。因此,音频系统无法识别流的格式并引发异常

    这不是故意的。您需要在流中提供完整的音频格式图像,以便AudioSystem识别流的格式,而不仅仅是原始数据