上篇文章讲解了怎么利用FFmpeg来合并一个音视频,今天我们继续来讲解一下利用FFmpeg来处理视频的时间,比如裁剪一段视频,然后合并输出新的视频地址,看了这篇文章你就能学会怎么处理音视频时间合并了。
![8fa5d647b01da863c32c3bda7a462e1e.png](https://i-blog.csdnimg.cn/blog_migrate/a13e6a81d363373198ff3b35448fa1b4.jpeg)
在讲解之前我在这里还是简单来说一下代码当中关于koltin的一些基础知识吧,
fun setCallback(callback: FFMpegCallback): AudioTrimmer { this.callback = callback return this }
这段代码是一个构造方法,kotlin当中跟java的命名是相反的,比如kotlin当中:冒号后面一般是跟的返回值类型,包括参数后面的冒号就是这个变量的类型。
class AudioTrimmer private constructor(private val context: Context) { private var audio: File? = null private var callback: FFMpegCallback? = null private var startTime = "00:00:00" private var endTime = "00:00:00" private var outputPath = "" private var outputFileName = "" fun setFile(originalFiles: File): AudioTrimmer { this.audio = originalFiles return this } fun setCallback(callback: FFMpegCallback): AudioTrimmer { this.callback = callback return this } fun setStartTime(startTime: String): AudioTrimmer { this.startTime = startTime return this } fun setEndTime(endTime: String): AudioTrimmer { this.endTime = endTime return this } fun setOutputPath(output: String): AudioTrimmer { this.outputPath = output return this } fun setOutputFileName(output: String): AudioTrimmer { this.outputFileName = output return this } fun trim() { if (audio == null || !audio!!.exists()) { callback!!.onFailure(IOException("File not exists")) return } if (!audio!!.canRead()) { callback!!.onFailure(IOException("Can't read the file. Missing permission?")) return } val outputLocation = Utils.getConvertedFile(outputPath, outputFileName) //Trim starting from start Time to End time val cmd = arrayOf("-i", audio!!.path, "-ss", startTime, "-t", endTime, "-c", "copy", outputLocation.path) try { FFmpeg.getInstance(context).execute(cmd, object : ExecuteBinaryResponseHandler() { override fun onStart() {} override fun onProgress(message: String?) { callback!!.onProgress(message!!) } override fun onSuccess(message: String?) { Utils.refreshGallery(outputLocation.path, context) callback!!.onSuccess(outputLocation, OutputType.TYPE_AUDIO) } override fun onFailure(message: String?) { if (outputLocation.exists()) { outputLocation.delete() } callback!!.onFailure(IOException(message)) } override fun onFinish() { callback!!.onFinish() } }) } catch (e: Exception) { callback!!.onFailure(e) } catch (e2: FFmpegCommandAlreadyRunningException) { callback!!.onNotAvailable(e2) } } companion object { val TAG = "AudioTrimmer" fun with(context: Context): AudioTrimmer { return AudioTrimmer(context) } }}
上面的代码也很简单,就是从外部获取一个视频的输入文件,加上开始时间和结束时间来裁剪一个视频的长度。
好了如果有不懂得可以评论里面我们一起来讨论。
关注,点赞,转发,谢谢你的支持。