【Android】使用MediaExtractor、MediaMuxer去掉视频文件中的音频数据_android 去掉视频音频_little_fat_sheep的博客-CSDN博客
java
void removeSound() {
try {
String path = Environment.getExternalStorageDirectory().getPath();
String filename = "no_sound_" + input_path.substring(input_path.lastIndexOf("/") + 1);
String output_path = path + File.separator + filename;
MediaExtractor mediaExtractor = new MediaExtractor();
mediaExtractor.setDataSource(input_path);
MediaMuxer mediaMuxer = new MediaMuxer(output_path, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
int input_size = 0;
int videoTrackIndex = -1;
int count = mediaExtractor.getTrackCount(); //获取轨道数
for (int i = 0; i < count; i++) {
MediaFormat format = mediaExtractor.getTrackFormat(i);
String mime = format.getString(MediaFormat.KEY_MIME);
if (mime.startsWith("video/")) { // mp4为"video/avc"
input_size = format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
mediaExtractor.selectTrack(i);
videoTrackIndex = mediaMuxer.addTrack(format);
break;
}
}
mediaMuxer.start();
int sampleSize = 0;
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
ByteBuffer buffer = ByteBuffer.allocate(input_size); //也可以设置为:500*1024
while ((sampleSize = mediaExtractor.readSampleData(buffer, 0)) > 0) {
info.offset = 0;
info.size = sampleSize;
info.flags = mediaExtractor.getSampleFlags();
info.presentationTimeUs = mediaExtractor.getSampleTime();
mediaMuxer.writeSampleData(videoTrackIndex, buffer, info); //写入数据
mediaExtractor.advance(); //下一帧
}
mediaExtractor.release();
mediaMuxer.stop();
mediaMuxer.release();
MediaScannerConnection.scanFile(MainActivity.this, new String[]{ output_path }, null, null);
Toast.makeText(getApplicationContext(), "视频生成完成:" + output_path, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
}
}
选择视频文件
java
String input_path = "";
void chooseFile() {
int CHOOSE_VIDEO = 200;
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, CHOOSE_VIDEO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
String[] proj = { MediaStore.Video.Media.DATA };
Cursor cursor = managedQuery(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
input_path = cursor.getString(column_index);
Log.e(Thread.currentThread().getStackTrace()[2] + "", input_path);
}
}