gpt4 book ai didi

java - 保存多 channel 音频文件

转载 作者:行者123 更新时间:2023-12-01 09:11:50 24 4
gpt4 key购买 nike

我正在尝试使用 Java Sound API 将两个数据缓冲区作为单独的 channel 输出到一个音频文件中。我找到了输出单声道音频的方法,但这并不是我真正想要的。我也不知道应该使用哪种音频格式(WAV、MP3 等)。我的两个数据缓冲区是范围从 -127 到 +127 的字节数组。

最佳答案

这里有一些示例代码,向您展示如何创建 WAV 文件。 Java 并没有真正支持 MP3,尽管有相应的库。

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

public class StereoOutput {

public static void main(final String[] args) throws IOException {

// left samples - typically more than 4!!
final byte[] left = new byte[] {1, 2, 3, 4};
// right samples
final byte[] right = new byte[] {1, 2, 3, 4};

final ByteArrayInputStream interleavedStream = createInterleavedStream(left, right);

// audio format of the stream we created
final AudioFormat audioFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
44100f, // sample rate - you didn't specify, 44.1k is typical
8, // how many bits per sample, i.e. per value in your byte array
2, // you want two channels (stereo)
2, // number of bytes per frame (frame == a sample for each channel)
44100f, // frame rate
true); // byte order
final int numberOfFrames = left.length; // one frame contains both a left and a right sample
// wrap stream into AudioInputStream (data + format)
final AudioInputStream audioStream = new AudioInputStream(interleavedStream, audioFormat, numberOfFrames);
// write to WAV file
AudioSystem.write(audioStream, AudioFileFormat.Type.WAVE, new File("out.wave"));
}

/**
* Typically in PCM audio, left and right samples are interleaved.
* I.e.: LR LR LR LR.
* One LR is also called a "frame".
*
* @param left array with left samples
* @param right array with right samples
* @return stream that contains all samples in LR LR interleaved order
*/
private static ByteArrayInputStream createInterleavedStream(final byte[] left, final byte[] right) {
final byte[] interleaved = new byte[left.length + right.length];
for (int i=0; i<left.length; i++) {
interleaved[2*i] = left[i];
interleaved[2*i+1] = right[i];
}
return new ByteArrayInputStream(interleaved);
}
}

我建议您通过 Java Sound Trail 进行操作还可以查看 Java API 文档中类似 AudioFormat 的类。如果您不熟悉PCM ,也阅读一下。这对于理解数字采样音频至关重要。

关于java - 保存多 channel 音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40873703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com