Pause/Resume other/system's MediaPlayer for a While - android

I have a requirement in one of my app in which I need to play an audio for a while on click of a button.
Now there comes a case if user is already playing music on device, then i need to pause that music player to play my sound and after I release my MediaPlayer object I want to resume other app's(or atleast system's) music player.
What I have managed to do is to gain audio focus like below -
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if (am!=null){
am.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener()
{
#Override
public void onAudioFocusChange(int focusChange) {
}},
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
}
But this snippet completely stops other app's music player and after releasing my MediaPlayer object AudioService is not giving focus back to system's music player.

You can use this code. For more info about onAudioFocusChangeListener
onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
#Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case (AudioManager.AUDIOFOCUS_LOSS):
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT):
pause();
break;
case (AudioManager.AUDIOFOCUS_GAIN):
resume();
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
// Lower the volume while ducking.
player.setVolume(0.1f, 0.1f);
break;
}
}
};
int mediaresult = audioManager.requestAudioFocus(onAudioFocusChangeListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (mediaresult == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//other app stop music you can play now
//put you play code here..
}

Use this :
public void musicPause() {
AudioManager mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if (mAudioManager.isMusicActive()) {
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause"); // you can give command here play,pause,resume and stop
playVideo.this.sendBroadcast(i); // playVideo is my Activity name
}
}

Related

How to play sound when headphone connected in android programatically?

I am working on one of the project which need to play sound simultaneously when headphone is connected.
I am using below code but no luck
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_NORMAL);
am.setSpeakerphoneOn(true);
You need to use a BroadcastReceiver to handle the action sent when the headset is plugged. You need after that to check if the action sent by the broadcast equals Intent.ACTION_HEADSET_PLUG in the onReceive method, then you can play your sound using MediaPlayer
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
//Headset is unplugged
break;
case 1:
//Headset is plugged
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
mediaPlayer.start();
break;
default:
Log.d(TAG, "I have no idea what the headset state is");
}
}
}
Please see this answer https://stackoverflow.com/a/13610712/2354845

Suppressing system audio volume to play notification audio from inside app

My app runs as a service in background and can give notifications based on some events. Currently, to play notification files, I use MediaPlayer in my app :
MediaPlayer mPlay = MediaPlayer.create(this, R.raw.sound);
mPlay.start();
But, if a song is already playing on the device (Music player, radio etc), and my notification plays when receiving the event, both the sounds (Music audio & notification audio) is heard in parallel.
So, is there a way that I can suppress the system audio volume so that my notification is heard clearly and once notification audio is over, the system audio can playback again?
Thanks for any help
I got the answer to this question in the following link:
http://developer.android.com/training/managing-audio/audio-focus.html
We need to request for audio focus (transient/permanent) and then can play the app audio:
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// Start playback.
Log.i(TAG, "...audiofocus granted....");
MediaPlayer mPlay = MediaPlayer.create(this, R.raw.sound);
mPlay.start();
}
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
// Pause playback
Log.i(TAG, "....audiofocus loss transient in listener......");
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Resume playback
Log.i(TAG, "....audiofocus gain in listener......");
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
Log.i(TAG, "....audiofocus loss in listener......");
//am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
am.abandonAudioFocus(afChangeListener);
// Stop playback
}
}
};
Hope it helps someone.

Dismiss the Keyguard without unlock sound

I am writing a replacement LockScreen, and using LayoutParams.DISSMISS_KEYGUARD as a Window flag is dismissing the Keyguard when switching on the screen and launching my LockScreen, however it always plays an lock sound when pressing the power button again, how can I surpress the lock sound?
you could use an AudioManager to turn the sound off in OnCreate then turn it back on later. You would also want to check if the sound is off to start so that you don't turn the sound on when it was off already
This to check sound state
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
case AudioManager.RINGER_MODE_VIBRATE:
silentMode = true;
break;
case AudioManager.RINGER_MODE_NORMAL:
silentMode = false;
break;
}
This to turn sound off
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
OR
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
This to turn sound on
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Of course you would probably make am a private variable so you don't need to declare it more than once. Like this.
public class MainActivity extends Activity {
//more variables
private AudioManager am;
private boolean silentMode;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//check sound state and set silentMode;
//more stuff
}
}
I don't really know when to turn the sound back on but a place to try maybe after the call to getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

Play alarm sound just once

I have a working alarm app, but wanted to add a feature where the user gets the choice between "Play alarm continuously till acknowledged" and "play alarm sound once".
I then looked at my alrm ringing code expecting to see some kind of "repeat" flag which I could optionally remove - but there was none. So how do I play the alarm sound just once?
My existing code looks like this:
private void playSound(Context context, Uri alert)
{
mMediaPlayer = new MediaPlayer();
try
{
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0)
{
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
}
catch (IOException e)
{
// oops!
}
}
Actually in each alarm sound there is a FLAG named ANDROID_LOOP which force your sound to loop. Unfortunatly you can't change that flag even using MediaPlayer.setLooping(false).
But you still can manually stop your player after a certain time. For example getDuration will give you the length of your sound.
int duration = mMediaPlayer.getDuration();
Runnable stopSoundRunnable = new Runnable() {
#Override
public void run() {
mMediaPlayer.stop();
}
};
mSoundHanlder.postDelayed(stopSoundRunnable, duration);

How to pause the background music while recording audio in android

I am developing an audio record application in android. So if any background music is already playing in the device music player, that should be paused before it starts recording and the background music should resume whenever the recording is either stopped or paused. And the same should work while playing the recorded audio. Can anybody help me out to get through this scenario? Thanks in advance..:)
get audioManager and check
audioManager.isMusicActive()
if true
private void toggleNativePlayer(Context context) {
Intent intent = new Intent("com.android.music.musicservicecommand");
intent.putExtra("command", "togglepause");
context.sendBroadcast(intent);
}
and after you finish recording run this code again to start play musig again
You can stop other applications from playing music, by requesting AudioFocus. When you are granted AudioFocus, other apps stop playing music and then you can play/record as per your needs.
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(focusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// other app had stopped playing song now , so you can start recording.
}
But, there is only one AudioManager. So, Audio focus is assigned to each application that requests it one by one. This means that if another application requests audio focus, your application will lose it. You will be notified of the loss of audio focus through the onAudioFocusChange handler of the Audio Focus Change Listener (afChangeListener) you registered when requesting the audio focus.
private OnAudioFocusChangeListener focusChangeListener =
new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch (focusChange) {
case (AudioManager.AUDIOFOCUS_LOSS) :
//Lost focus. Stop recording
break;
case (AudioManager.AUDIOFOCUS_GAIN) :
//Gained AudioFocus. Start recording tasks
break;
default: break;
}
}
};

Categories

Resources