3
votes

I have the following requirement.

I am developing an Android mobile application. A timer has been set for a specific duration for an activity.

  1. I need to play "beep" sound three times when the timer duration is 10 seconds left to complete (i.e. become zero), two times "beep" sound when the timer duration is 5 seconds left to complete & once "beep" sound when the timer completes.

  2. The user may be playing music using the default music player of the Android phone while using the Android mobile application. I need to implement the logic so that when the "beep" sound is being played from the mobile application, I need to first decrease the volume of the default music & then play the "beep" sound & again reset to the original volume after the "beep" sound have been played the required no of times.

I wanted to know, whether this is technically feasible or not.

2

2 Answers

3
votes

Yes, you can use AudioManager to change the volume for music. The function [setStreamVolume][2] is what you're looking for. The stream type you're looking for is AudioManager.STREAM_MUSIC

[2]: http://developer.android.com/reference/android/media/AudioManager.html#setStreamVolume(int, int, int)

1
votes

One way to achieve this is by using the platform's ability to allow your app to request audio focus while allowing other apps to "duck". This allows you to tell the system .. "Hey, I'm going to play something, tell other apps also playing audio that it's ok to continue playing but to lower their volume".

Here is the relevant sample code and note from the Managing Audio Focus section.

When requesting transient audio focus you have an additional option: whether or not you want to enable "ducking." Normally, when a well-behaved audio app loses audio focus it immediately silences its playback. By requesting a transient audio focus that allows ducking you tell other audio apps that it’s acceptable for them to keep playing, provided they lower their volume until the focus returns to them.

AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
                             // Use the music stream.
                             AudioManager.STREAM_NOTIFICATION,
                             //tell them it's ok to duck
                             AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    // Start playback.
}

I hope it helps someone.