I am trying to play sound on speaker even if headphones are on, BUT if there is music playing in background, I want the music to be played on headphones until the sound is played.
So I am taking the next steps:
- Before I play sound, I gain audioFocus so all the background music is stopped
- After audioFocus is gained, I set
MODE_COMMUNICATION
to the AudioManager, so the sound can be played on the speaker. - After the sound ends, I abandonAudioFocus and set back
MODE_NORMAL
toAudioManager
, so the background music can continue playing on the headphones.
The strange thing is that it depends from the device, on some device this is OK, but on Nexus 6P (Huawei) devices after setting the MODE_COMMUNICATION
there is delay 3-4 seconds before the sound can be played. If I play the sound without the delay, it is not played neither to speaker nor to headphones.
THE QUESTION
How can I know how much delay to set before the sound is played? Is there any listener that I can attach, so can notify me that after setting MODE_COMMUNICATION
the sound is ready to be played?
I don't want to set delay even if it is not necessary!
The solution is not setting the mode into the constructor of the class(to skip the delay), because I need the sound to be played on speaker in the specific moment!
P.S: I am playing the sound with AudioTrack
, but I tried with MediaPlayer
as well (setting setAudioStreamType(MODE_IN_COMMUNICATION)
), but no success, the delay is still there!
So any suggestions?