应答呼叫时触发音频文件

时间:2011-06-18 11:59:33

标签: android audio phone-call

有没有办法在接听电话时启动音频文件而不是在通话中播放(因此对方可以听到),但只能在通话扬声器中播放(因此只有我们这边可以听到)。

听起来很奇怪,我知道但它是一个更大的应用程序的一部分。

2 个答案:

答案 0 :(得分:1)

首先,您需要设置BroadcastReceiver(让我们称之为“CallReceiver”),以及了解手机状态的权限(直观地说,添加权限为android.permission.READ_PHONE_STATE )。

像这样注册你的CallReceiver动作。

<receiver android:name=".CallReceiver" android:enabled="true">
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE"></action>
    </intent-filter>
</receiver>

在您的CallReceiver中,您可以决定您的音频应该播放哪些动作(传入/传出/电话响铃......),所以只需阅读EXTRA_STATE和getCallState()(查看TelephonyManager文档)。

关于音频,您需要使用AudioManager,并在播放声音之前设置播放时的“通话中”模式。

private AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);  
am.setMode(AudioManager.MODE_IN_CALL); 
am.setSpeakerphoneOn(false);

我希望这有帮助!

答案 1 :(得分:0)

  private void PlayShortAudioFileViaAudioTrack(String filePath) throws IOException {
 // We keep temporarily filePath globally as we have only two sample sounds now..
         if (filePath == null)
             return;

 //Reading the file..
         byte[] byteData = null;
         File file = null;
         file = new File(filePath); // for ex. path= "/sdcard/samplesound.pcm" or "/sdcard/samplesound.wav"
         byteData = new byte[(int) file.length()];
         FileInputStream in = null;
         try {
             in = new FileInputStream(file);
             in.read(byteData);
             in.close();

         } catch (FileNotFoundException e) {
 // TODO Auto-generated catch block
             e.printStackTrace();
         }
 // Set and push to audio track..
         int intSize = android.media.AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                 AudioFormat.ENCODING_PCM_8BIT);
         AudioTrack at = new AudioTrack(AudioManager.STREAM_VOICE_CALL, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                 AudioFormat.ENCODING_PCM_8BIT, intSize, AudioTrack.MODE_STREAM);
         if (at != null) {
             at.play();
 // Write the byte array to the track
             at.write(byteData, 0, byteData.length);
             at.stop();
             at.release();
         } else
             Log.d("TCAudio", "audio track is not initialised ");