我正在尝试将方法从 java 转换为 kotlin 并替换AsyncTask
为协程,但我不知道如何从协程返回值
这是我的方法
override fun getCompressedVideo(context:Context ,video: Uri) {
GlobalScope.launch(Dispatchers.Main) {
val inputFile = video.getRealPathFromVideoUri(context)
val loadJNI: LoadJNI = LoadJNI();
try {
val workFolder: String = context.filesDir.absolutePath
val outputFile: String = getFileFullName(
FilesConstants.VIDEO_FOLDER,
String.format(FilesConstants.VIDEO_NAME_FILE_FORMAT, System.currentTimeMillis())
);
val complexCommand = arrayOf (
"ffmpeg", "-y"
, "-i", inputFile
, "-strict", "experimental"
, "-s", "320x240"
, "-r", "25"
, "-aspect", "4:3"
, "-ab", "48000"
, "-ac", "2"
, "-vcodec", "mpeg4"
, "-movflags", "+faststart"
, "-ar", "22050"
, "-b", "2097k"
, outputFile);
loadJNI.run(complexCommand, workFolder, context);
return outputFile
} catch (th: Throwable) {
return@launch
}
}
}
返回 outputFile的行编译出错,谁能帮忙,这是我第一次使用协程
编辑
这是使用挂起后的方法,但是现在我不知道如果发生任何问题我该如何返回值
override suspend fun getCompressedVideo(context: Context, video: Uri) {
val outputFile = withContext(Dispatchers.IO) {
val inputFile = video.getRealPathFromVideoUri(context)
val loadJNI: LoadJNI = LoadJNI();
try {
val workFolder: String = context.filesDir.absolutePath
val outputFile: String = getFileFullName(
FilesConstants.VIDEO_FOLDER,
String.format(FilesConstants.VIDEO_NAME_FILE_FORMAT, System.currentTimeMillis())
);
val complexCommand = arrayOf(
"ffmpeg", "-y"
, "-i", inputFile
, "-strict", "experimental"
, "-s", "320x240"
, "-r", "25"
, "-aspect", "4:3"
, "-ab", "48000"
, "-ac", "2"
, "-vcodec", "mpeg4"
, "-movflags", "+faststart"
, "-ar", "22050"
, "-b", "2097k"
, outputFile
);
loadJNI.run(complexCommand, workFolder, context)
}catch (th: Throwable) {
}
}
}
编辑 2
你的意思是这样
override suspend fun getCompressedVideo(context: Context, video: Uri) : String {
try {
val retValue = withContext(Dispatchers.IO) {
val inputFile = video.getRealPathFromVideoUri(context)
val loadJNI: LoadJNI = LoadJNI()
val workFolder: String = context.filesDir.absolutePath
val outputFile: String = getFileFullName(
FilesConstants.VIDEO_FOLDER,
String.format(FilesConstants.VIDEO_NAME_FILE_FORMAT, System.currentTimeMillis())
)
val complexCommand = arrayOf(
"ffmpeg", "-y"
, "-i", inputFile
, "-strict", "experimental"
, "-s", "320x240"
, "-r", "25"
, "-aspect", "4:3"
, "-ab", "48000"
, "-ac", "2"
, "-vcodec", "mpeg4"
, "-movflags", "+faststart"
, "-ar", "22050"
, "-b", "2097k"
, outputFile
)
loadJNI.run(complexCommand, workFolder, context)
}
return retValue.toString()
} catch (th: Throwable) {
return ""
}
}
并称它为
GlobalScope.launch {
val retValue = ffmpegFacade.getCompressedVideo(this@TestActivity, Uri.parse(""))
}