我尝试使用Java Sound(带MP3SPI和VorbisSPI)从WAV,MP3和OGG文件中读取音频数据,将其存储到字节数组中,以便播放它从那以后。为此,我使用这样的代码:
public Sound loadSound(File file){
AudioInputStream baseStream = AudioSystem.getAudioInputStream(file);
AudioFormat baseFormat = baseStream.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
AudioInputStream decodedStream = AudioSystem.getAudioInputStream(decodedFormat, baseStream);
// Buffer audio data from audio stream
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int nBytesRead = 0;
while (nBytesRead != -1) {
nBytesRead = decodedStream.read(buffer, 0, buffer.length);
// Write read bytes to out stream
byteOut.write(buffer);
}
// close streams and cleanup
byte[] samples = byteOut.toByteArray();
return new Sound(samples,decodedFormat);
}
Sound类基本上是一个(byte []样本,AudioFormat格式)耦合。完成后,我尝试按如下方式读取和播放字节数组:
public void play(Sound sound) {
InputStream source = new ByteArrayInputStream(sound.getSamples());
AudioFormat format = sound.getFormat();
// use a short, 100ms (1/10th sec) buffer for real-time changes to the sound stream
int bufferSize = format.getFrameSize()
* Math.round(format.getSampleRate() / 10);
byte[] buffer = new byte[bufferSize];
// create a line to play to
SourceDataLine line;
try {
DataLine.Info info
= new DataLine.Info(SourceDataLine.class, format);
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format, bufferSize);
} catch (LineUnavailableException ex) {
ex.printStackTrace();
return;
}
// start the line
line.start();
// copy data to the line
try {
int numBytesRead = 0;
while (numBytesRead != -1) {
numBytesRead
= source.read(buffer, 0, buffer.length);
if (numBytesRead != -1) {
line.write(buffer, 0, numBytesRead);
}
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (ArrayIndexOutOfBoundsException ex2) {
}
// wait until all data is played, then close the line
line.drain();
line.close();
}
这一切都适用于WAV和MP3,但OGG播放失真并有所减慢,就像格式错误一样。如果有人能指出为什么会发生这种情况,我会很高兴。
注意:我通过将整个音频文件作为带有FileInputStream的字节数组加载,然后通过阵列上的ByteArrayInputStream与AudioInputStream一起播放来解决了这个问题。但是,这种方式,字节数组保存编码数据而不是解码数据:在实践中,对我来说没有太大区别,但我很好奇为什么以前的方法对OGG不起作用。 感谢所有试图回答的人。
答案 0 :(得分:2)
问题出在loadSound
,其中nBytesRead
返回值未在以下write
调用中使用。返回请求的完整字节数不需要read
函数。实际上,如果解码器可以沿着其自然边界破坏,它可能使解码器更容易实现。这可能是ogg解码器正在做的事情。此外,如果未使用返回值,则非常读取的调用不太可能返回确切的请求大小。
byte[] buffer = new byte[4096];
int nBytesRead = 0;
while (nBytesRead != -1) {
nBytesRead = decodedStream.read(buffer, 0, buffer.length);
// Write read bytes to out stream
byteOut.write(buffer, 0, nBytesRead);
// ^^^^^^^^^^^^^
}