我正在开发一个用于通话录音的应用程序。在 Main Activity 中,我要求获得录制通话所需的所有权限。在广播接收器中,我分别处理传入和传出呼叫以及录音。但应用程序显示错误,表明媒体记录器无法启动。据我了解,在声明文件路径之前代码运行良好。当我声明 filepath 时,应用程序在接到电话时崩溃。我认为 Definefilepath() 中存在一些问题,或者我调用它的时间不对。
广播接收器代码
CallReciever 类:BroadcastReceiver() {
private val mediaRecorder = MediaRecorder()
lateinit var filePath : String
override fun onReceive(context: Context?, intent: Intent?) {
if(intent?.action == TelephonyManager.ACTION_PHONE_STATE_CHANGED){
val state = intent.getStringExtra(TelephonyManager.EXTRA_STATE)
when(state){
TelephonyManager.EXTRA_STATE_RINGING->{
//Handle incoming call - start recording
val incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)
callRecorder()
Log.i("anshi","call recieved and Call Recording is going on")
}
TelephonyManager.EXTRA_STATE_OFFHOOK->{//perform actions when an outgoing call is answered
//Handle call answered - store recording
callRecorder()
Log.i("anshi","call outgoing and Call Recording is going on")
}
TelephonyManager.EXTRA_STATE_IDLE->{//perform actions when a call ends.
//Handle call ended - end recording
Log.i("anshi","call has ended")
mediaRecorder.stop()
mediaRecorder.reset()
mediaRecorder.release()
}
}
}
}
private fun defineFilePath() {
val directory = File(Environment.getExternalStorageDirectory(), "Recordings")
directory.mkdirs()
val fileName = "recording_${System.currentTimeMillis()}.mp3"
filePath = File(directory, fileName).absolutePath
Log.i("anshi","defined file path")
}
private fun callRecorder() {
defineFilePath()
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL)
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
mediaRecorder.setOutputFile(filePath)
try {
// Prepare the MediaRecorder
mediaRecorder.prepare()
// Start the recording
mediaRecorder.start()
} catch (e: IOException) {
// Handle any exceptions that occur during recording
}
}
}
正如 @Robert 所说,通话录音在最近的 Android 版本上存在问题。
我收到了制作通话录音应用程序的任务,我现在该怎么做?
现在,您可以在最新的 Android 版本上使用辅助功能服务来执行此操作。但这样你就无法将你的应用程序发布到 Play 商店