java
// 设置 FFmpeg 日志回调,以便打印详细的 FFmpeg 日志
FFmpegLogCallback.set();
FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
grabber.start();
int audioChannels = grabber.getAudioChannels();
int audioSampleRate = grabber.getSampleRate();
int audioBitrate = grabber.getAudioBitrate();
//视频质量,0最高,50最低
double audioQuality = 0;
//直接获取的音频format不能使用,这里指定
String audioFormat = "mp3";
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, audioChannels);
//这里有一个对应关系,代码九不列出了,具体编码在 org.bytedeco.ffmpeg.global.avcodec 类中,如 avcodec.AV_CODEC_ID_MP3
int audioCodec = Util.audioCodecMatch(audioFormat);
// 设置音频
recorder.setSampleRate(audioSampleRate);
recorder.setAudioBitrate(audioBitrate);
if (audioCodec != -1) {
recorder.setAudioCodec(audioCodec);
}
recorder.setFormat(audioFormat);
recorder.setAudioQuality(audioQuality);
recorder.start();
Frame frame;
//这里指定裁剪的时间区间
long start = TimeUnit.MICROSECONDS.convert(startMs, TimeUnit.MILLISECONDS);
long end = TimeUnit.MICROSECONDS.convert(endMs, TimeUnit.MILLISECONDS);
while ((frame = grabber.grabSamples()) != null) {
//grabber.getTimestamp() 返回的是微秒(us)
long frameNumber = grabber.getTimestamp();
if (frameNumber >= start * 1000 && frameNumber <= end * 1000) {
recorder.record(frame);
}
if (frameNumber > end) {
break;
}
}
recorder.stop();
grabber.stop();
这段代码不影响使用,但是根据打印的日志,总会有几帧没有处理,可能和设置的buffer有关,了解怎么解决的麻烦在评论区写一下,大家一起进步。