CraigInDallas
CraigInDallas

Reputation: 227

Trigger an audio file when call is answered

Is there a way to launch an audio file when answering a call to be played NOT into the call (so the other side could hear), but only in the call speaker (so only our side could hear).

Sounds strange, I know but it is part of a much larger app.

Upvotes: 8

Views: 4229

Answers (2)

Akshay Shah
Akshay Shah

Reputation: 788

  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 ");

Upvotes: 0

Alberto Rico
Alberto Rico

Reputation: 405

First of all, you'll need to set up a BroadcastReceiver (let's call it "CallReceiver"), and permission to know about the phone state (intuitively, the permission to add is android.permission.READ_PHONE_STATE).

Register your CallReceiver action like this.

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

At your CallReceiver, you may decide upon which actions should your audio play back (incoming/outcoming/phone ringing...), so just read the EXTRA_STATE, and getCallState() (check out the TelephonyManager docs).

About the audio, you will need to use the AudioManager, and set the "in call" mode of playback before playing the sound.

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

I hope this helps!

Upvotes: 1

Related Questions