这个问题有点过于复杂.我知道如何实现它.
这里是从视频文件中提取音频数据的代码,但它是PCM数据,而不是mp3:
public class AudioFromVideo{
private String audio,video;
private MediaCodec amc;
private MediaExtractor ame;
private MediaFormat amf;
private String amime;
public AudioFromVideo(String srcVideo,String destAudio){
this.audio=destAudio;
this.video=srcVideo;
ame=new MediaExtractor();
init();
}
public void init(){
try {
ame.setDataSource(video);
amf=ame.getTrackFormat(1);
ame.selectTrack(1);
amime=amf.getString(MediaFormat.KEY_MIME);
amc=MediaCodec.createDecoderByType(amime);
amc.configure(amf, null, null, 0);
amc.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public void start(){
new AudioService(amc,ame,audio).start();
}
private class AudioService extends Thread{
private MediaCodec amc;
private MediaExtractor ame;
private ByteBuffer[] aInputBuffers,aOutputBuffers;
private String destFile;
@SuppressWarnings("deprecation")
AudioService(MediaCodec amc,MediaExtractor ame,String destFile){
this.amc=amc;
this.ame=ame;
this.destFile=destFile;
aInputBuffers=amc.getInputBuffers();
aOutputBuffers=amc.getOutputBuffers();
}
@SuppressWarnings("deprecation")
public void run(){
try {
OutputStream os=new FileOutputStream(new File(destFile));
long count=0;
while(true){
int inputIndex=amc.dequeueInputBuffer(0);
if(inputIndex==-1){
continue;
}
int sampleSize=ame.readSampleData(aInputBuffers[inputIndex], 0);
if(sampleSize==-1)break;
long presentationTime=ame.getSampleTime();
int flag=ame.getSampleFlags();
ame.advance();
amc.queueInputBuffer(inputIndex, 0, sampleSize, presentationTime, flag);
BufferInfo info=new BufferInfo();
int outputIndex=amc.dequeueOutputBuffer(info, 0);
if (outputIndex >= 0) {
byte[] data=new byte[info.size];
aOutputBuffers[outputIndex].get(data, 0, data.length);
aOutputBuffers[outputIndex].clear();
os.write(data);
count+=data.length;
Log.i("write", ""+count);
amc.releaseOutputBuffer(outputIndex, false);
} else if (outputIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
aOutputBuffers = amc.getOutputBuffers();
} else if (outputIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {}
}
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
例如,要从视频文件video.mp4中提取音频数据,并将提取的日期保存到audio.pcm文件中,请编写如下代码:
String videoPath=PATH+"/video.mp4";
String audioPath=PATH+"/audio.pcm";
new AudioFromVideo(video.audio).start();
如果您需要mp3数据,可以使用lame mp3 lib将PCM数据编码为MP3格式.我有所有代码.但是将它们全部粘贴在这里并不值得.