今天开始就讲解工具类的开发,AudioExtractor 音频的提取类,一个音视频包含了音频和视频,我们在拿到一个mp4文件过后,如果自己写一个播放器就需要解析里面的音频和视频。
这个工具类就是来解析音频里面的音频提取,需要用到的知识点有文件,文件异常IOException,FFmpeg 也是一个开源库,就是一个指令来提取视频里面的音频:
val cmd = arrayOf("-i", video!!.path, "-vn", "-ar", "44100", "-ac", "2", "-ab", "192", "-f", "mp3", outputLocation.path)
有了这个工具类就很方便的把视频里面的音频给提取出来了
class AudioExtractor private constructor(private val context: Context) {
private var video: File? = null
private var callback: FFMpegCallback? = null
private var outputPath = ""
private var outputFileName = ""
fun setFile(originalFiles: File): AudioExtractor {
this.video = originalFiles
return this
}
fun setCallback(callback: FFMpegCallback): AudioExtractor {
this.callback = callback
return this
}
fun setOutputPath(output: String): AudioExtractor {
this.outputPath = output
return this
}
fun setOutputFileName(output: String): AudioExtractor {
this.outputFileName = output
return this
}
fun extract() {
video?.let {
if (!video!!.exists()) {
callback!!.onFailure(IOException("File not exists"))
return
}
if (!video!!.canRead()) {
callback!!.onFailure(IOException("Can't read the file. Missing permission?"))
return
}
val outputLocation = Utils.getConvertedFile(outputPath, outputFileName)
//Create Audio File with 192Kbps
//Select .mp3 format
val cmd = arrayOf("-i", video!!.path, "-vn", "-ar", "44100", "-ac", "2", "-ab", "192", "-f", "mp3", 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 = "AudioExtractor"
fun with(context: Context): AudioExtractor {
return AudioExtractor(context)
}
}
}
上面就完成了音频的提取了完成了。
我是一个北上广回回重庆的程序员坚持在写代码,记得点赞,关注,转发,谢谢了。