android mp3转pcm
时间: 2023-11-06 18:15:09 浏览: 124
可以使用Android中的MediaExtractor和MediaCodec类来实现mp3到pcm的转换。
以下是一个简单的示例代码:
```java
private void convertMP3toPCM(String mp3FilePath, String pcmFilePath) throws IOException {
MediaExtractor extractor = new MediaExtractor();
extractor.setDataSource(mp3FilePath);
int trackIndex = selectTrack(extractor);
extractor.selectTrack(trackIndex);
MediaCodec codec = MediaCodec.createDecoderByType("audio/mpeg");
codec.configure(extractor.getTrackFormat(trackIndex), null, null, 0);
codec.start();
ByteBuffer[] inputBuffers = codec.getInputBuffers();
ByteBuffer[] outputBuffers = codec.getOutputBuffers();
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
boolean isEOS = false;
long presentationTimeUs = 0;
FileOutputStream fos = new FileOutputStream(pcmFilePath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while (!isEOS) {
int inIndex = codec.dequeueInputBuffer(10000);
if (inIndex >= 0) {
ByteBuffer buffer = inputBuffers[inIndex];
int sampleSize = extractor.readSampleData(buffer, 0);
if (sampleSize < 0) {
codec.queueInputBuffer(inIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
isEOS = true;
} else {
codec.queueInputBuffer(inIndex, 0, sampleSize, presentationTimeUs, 0);
presentationTimeUs = extractor.getSampleTime();
extractor.advance();
}
}
int outIndex = codec.dequeueOutputBuffer(info, 10000);
switch (outIndex) {
case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED:
outputBuffers = codec.getOutputBuffers();
break;
case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED:
break;
case MediaCodec.INFO_TRY_AGAIN_LATER:
break;
default:
ByteBuffer buffer = outputBuffers[outIndex];
byte[] chunk = new byte[info.size];
buffer.get(chunk);
buffer.clear();
bos.write(chunk);
codec.releaseOutputBuffer(outIndex, false);
break;
}
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
isEOS = true;
}
}
codec.stop();
codec.release();
extractor.release();
bos.flush();
bos.close();
fos.close();
}
private int selectTrack(MediaExtractor extractor) {
// Select the first audio track we find.
int numTracks = extractor.getTrackCount();
for (int i = 0; i < numTracks; i++) {
MediaFormat format = extractor.getTrackFormat(i);
String mime = format.getString(MediaFormat.KEY_MIME);
if (mime.startsWith("audio/")) {
return i;
}
}
return -1;
}
```
需要注意的是,这段代码中的`selectTrack`方法用于选择第一个音频轨道,如果需要处理其他轨道,请根据实际情况进行修改。
阅读全文