当我在模拟器中运行以下代码时,呼叫开始并且当呼叫断开时它在调用停止函数时显示 NullPointerException 并且当使用 VOICE_CALL 作为音频源时输出是一个空文件。但是当我将 VOICE_UPLINK 作为音频源时有效(仍然存在空指针异常)。当我在设备中运行它时,一旦拨打号码,它就会显示 FileNotFound 异常和 Permission Denied。但是我已经在清单文件中提供了所需的权限。
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
我只从互联网上得到了这里和那里的代码。我做的是一场彻底的灾难。完整的课程代码:
public class ServiceReceiver extends BroadcastReceiver {
PhoneStateListener listener;
TelephonyManager telephony;
MediaRecorder recorder = new MediaRecorder();
@Override
public void onReceive(Context context, Intent intent) {
telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch(state)
{
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d("DEBUG", "OFFHOOK");
StartRecording();
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.d("DEBUG", "IDLE");
StopRecording();
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.d("DEBUG", "RINGING");
break;
}
}
public void StartRecording(){
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(this.getFullSdPath());
try {
recorder.prepare();
Log.i(this.getClass().getName(), "Prepared");
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i(this.getClass().getName(), "ERR 1");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i(this.getClass().getName(), "ERR 2");
}
recorder.start(); // Recording is now started
Log.i(this.getClass().getName(), "Start Recording");
}
public void StopRecording(){
recorder.stop();
recorder.release();
recorder = null;
Log.i(this.getClass().getName(), "Stop Recording");
}
public String getFullSdPath(){
File sdCard = new File(Environment.getExternalStorageDirectory() + "/RecordMyVoice");
if (!sdCard.exists()) {
sdCard.mkdir();
}
File file = new File(Environment.getExternalStorageDirectory()+"/RecordMyVoice/",new Date().getTime()+".mp4");
System.out.println("Full path of record sound is : "+file.getAbsolutePath());
return file.getAbsolutePath();
}
};
telephony.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
难道我做错了什么?我听说在 Android 中无法轻松制作通话录音应用程序。