当我尝试通过音轨播放 pcm 数据时,我使用 jLayer lib 解码了 mp3,这会产生很多音频失真。
我的解码器代码:
public static void decode(String path, int startMs, int maxMs)
throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024);
float totalMs = 0;
boolean seeking = true;
File file = new File(path);
System.out.println("the data "+path);
InputStream inputStream = new BufferedInputStream(new FileInputStream(file), 8 * 1024);
try {
Bitstream bitstream = new Bitstream(inputStream);
Decoder decoder = new Decoder();
boolean done = false;
while (! done) {
javazoom.jl.decoder.Header frameHeader = bitstream.readFrame();
if (frameHeader == null) {
done = true;
} else {
totalMs += frameHeader.ms_per_frame();
if (totalMs >= startMs) {
seeking = false;
}
if (! seeking) {
SampleBuffer output = (SampleBuffer) decoder.decodeFrame(frameHeader, bitstream);
if (output.getSampleFrequency() != 44100
|| output.getChannelCount() != 2) {
// throw new com.mindtherobot.libs.mpg.DecoderException("mono or non-44100 MP3 not supported");
}
short[] pcm = output.getBuffer();
byte[] bs;
int index=0;
ByteBuffer buffer;
buffer = ByteBuffer.allocate(2*pcm.length);
for (short s : pcm) {
// outStream.write(s & 0xff);
// outStream.write((s >> 8 ) & 0xff);
buffer.putShort(s);
}
byte[] dataaudio = buffer.array();
//return buffer.array();
track.write(dataaudio, 0, dataaudio.length);
}
if (totalMs >= (startMs + maxMs)) {
done = true;
}
}
bitstream.closeFrame();
}
//return outStream.toByteArray();
} catch (BitstreamException e) {
throw new IOException("Bitstream error: " + e);
} catch (DecoderException e) {
Log.w("data", "Decoder error", e);
;
} finally {
// IOUtils.safeClose(inputStream);
}
}