.wav选择器,将声音写入阵列

时间:2013-12-17 22:01:53

标签: java arrays wav jfilechooser

我选择.wav使用我所拥有的类框架:

JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
    InputStream in = null;
    try {
        in = new FileInputStream(chooser.getSelectedFile().getAbsolutePath());
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        as = new AudioStream(in);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

接下来,我想在下面运行方法。这个方法应该播放.wav并将声音写入一个字节数组,但我有错误:

java.io.IOException: cannot read a single byte if frame size > 1

AudioInputStream stream;
stream = AudioSystem.getAudioInputStream(Frame.as);
// Get Audio Format information
AudioFormat audioFormat = stream.getFormat();

// Handle opening the line
SourceDataLine line = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,audioFormat);
try {
    line = (SourceDataLine) AudioSystem.getLine(info);
    line.open(audioFormat);
} catch (LineUnavailableException e) {
    e.printStackTrace();
    System.exit(1);
} catch (Exception e) {
    e.printStackTrace();
    System.exit(1);
}

// Start playing the sound
line.start();

// Write the sound to an array of bytes
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
while (nBytesRead != -1) {
    try {
        nBytesRead = stream.read(abData, 0, abData.length);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (nBytesRead >= 0) {
        int nBytesWritten = line.write(abData, 0, nBytesRead);
    }
}

// close the line
line.drain();
line.close();

代码有什么问题?

1 个答案:

答案 0 :(得分:0)

如果查看AudioInputStream#readSourceDataLine#write的文档,您将看到要读/写的字节数必须是整数个样本帧。在您的情况下,看起来EXTERNAL_BUFFER_SIZE为1,音频格式必须大于8位。

由于整数规则,不要根据您正在进行的静态常量创建缓冲区。通过将nBytesRead传递给write,您几乎可以得到它,但您需要考虑音频的样本大小。相反,用这样的东西创建你的字节缓冲区:

byte[] abData = new byte[
    audioFormat.getFrameSize() * EXTERNAL_BUFFER_SIZE
];

现在,您的缓冲区代表整数样本框中的大小。