This question is a little too complex. I know how to implement it.
here is the code to extract audio data from video file ,but it's PCM data ,not 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();
}
}
}
}
For example ,to extract audio data from Video file video.mp4,and save the extracted date into file audio.pcm,write code like this:
String videoPath=PATH+"/video.mp4";
String audioPath=PATH+"/audio.pcm";
new AudioFromVideo(video.audio).start();
If you need mp3 data,you can use lame mp3 lib to encode PCM data to MP3 format.I have all the code. but it is not convinent to paste all of them here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…