Android stop sounds - android

I am writing an alert app. When an alert is received, I want to stop all current sounds (like music) and play my alert sound. After the user has done something and the activity will be closed, the previous sounds should continue.
Thats the same like someone calls you. How can I achieve this behaviour?

You can request audio focus. Once you are done with your own audio, abandon audio focus so other apps can start playing sound again. You will be notified of other apps requesting audio focus too, thus being able to pause and resume your own sounds.
Requesting audio focus:
AudioManager am = mContext.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);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
am.registerMediaButtonEventReceiver(RemoteControlReceiver);
// Start playback.
}

With the help of Julius Skripkauskas' answer I use the following code:
to start the alert sound:
private void playSound(){
try{
Log.d(TAG, "request audio focus");
this.am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
int result=this.am.requestAudioFocus(afListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE);
if(result==AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
Log.d(TAG, "audio focus granted");
this.player=new MediaPlayer();
this.player.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}});
this.player.setOnCompletionListener(new OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mp) {
am.abandonAudioFocus(afListener);
}});
this.player.setAudioStreamType(AudioManager.STREAM_MUSIC);
this.player.setDataSource(getApplicationContext(), Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound ));
this.player.prepareAsync();
}
}catch(Exception e){
Log.e(TAG, "error playing music." + e.getMessage(), e);
}
}
The Listener:
I simply stop the sound because I will only play the sound once focus was granted. If the sound will get interrupted by an other app, it doesn't matter...
private AudioManager.OnAudioFocusChangeListener afListener = new AudioManager.OnAudioFocusChangeListener(){
#Override
public void onAudioFocusChange(int focusChange) {
Log.d(TAG, "audio focus changed" + Integer.toString(focusChange));
if(player==null){
// we don't play audio
return;
}
player.stop();
}};
It is important to consider to add the OnCompletionListener to the player where to call am.abandonAudioFocus(afListener) to release the audio focus immediately after the sound was played.

Related

How to pause background music if some activity have video to play in android?

There's some way to pause background music if on another activity have a video to play?
I've using this code to play music in all activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.ultahcover);
mediaPlayer.start();
memories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.pause();
length=mediaPlayer.getCurrentPosition();
startActivity(new Intent(MainActivity.this, kenangan_kita.class));
}
// here's an activity with video player
});
#Override
protected void onPause() {
super.onPause();
mediaPlayer.isPlaying(); //this is work to play on all activity but clashes with video music
}
any idea to avoid clashes music player?
please help me
Just request the audio focus, this will notify other apps that you need the focus now, and they should pause their playback:
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);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// Start playback
}
Take a look on this official guide: Handling Changes in Audio Output

How to play/stop/play again using MediaPlayer [duplicate]

This question already has answers here:
Media Player start stop start
(8 answers)
Closed 6 years ago.
I have a button when clicked it plays an audio, and while it is playing I can pause it and replay it again and so forth. I have a shake event, where I want to play the audio on shake and replay it when device is shaken again (by first stopping the audio, calling stopAudio?)
I have the following code:
llBtn = (LinearLayout) findViewById(R.id.button);
llBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(MainActivity.this, "LL WAS CLICKED", Toast.LENGTH_SHORT).show();
//IF AUDIO IS NOT PLAYING... PLAY AUDIO
if (tvPS.getText() == "Stop Phrase!") {
StopAudio();
}
else {
PlayAudio();
}
}
});
//the same button is clicked to stop, it is currently setting to Pause.
public void StopAudio() {
mediaPlayer.pause();
Toast.makeText(MainActivity.this, "STOPPED", Toast.LENGTH_SHORT).show();
tvPS.setText("Play Phrase!");
}
public void PlayAudio() {
//stopPlaying(mediaPlayer);
tvPS.setText("Stop Phrase!");
inResId = getResources().getIdentifier("play" , "raw", getPackageName());
mediaPlayer = MediaPlayer.create(getBaseContext(), inResId);
mediaPlayer.seekTo(0);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(MainActivity.this, "Done", Toast.LENGTH_SHORT).show();
tvPS.setText("Play Phrase!");
mediaPlayer.pause();
}
});
}
...
public void onShake() {
// Do stuff!
Toast.makeText(getBaseContext(), "Motion detected",
Toast.LENGTH_SHORT).show();
if (mediaPlayer == null) {
PlayAudio();
}
}
How can I modify the code above to handle Play, and then stop if stopped in the middle and then able to replay it again.
The button click works but I am creating a new instance each time and not recycling. When the device is shaken, it plays the audio twice instead of just once.
First of all create the MediaPlayer in onCreate of the context and not in some listener, and don't forget to release it when done, since it consumes a lot of resources,
mediaPlayer.release();
mediaPlayer = null;
Next thing, stop the audio using the stop() function instead of the pause() on completion of the song.
Steps
If you are using a service/activity to play a video create a MediaPlayer instance before it's usage begins, likely in onCreate.
Later use that instance to play/pause/stop the media.
In the onStop of the Service/Activity release the MediaPlayer instance.
Update your playMusic() function to use the MediaPlayer instance you just created, also in the listener use stop() instead of pause()
To change track of an existing MediaPlayer instance
You can use this:
String path = getExternalFilesDir(null).toString()+"/";
mMediaPlayer.setDataSource(path + mediafile);
Link: Changing data source for audio playback using existing MediaPlayer?

Stopping my audio when other audio has started playing on the device

I am playing an audio using MediaPlayer class. I have a requirement where audio played by my app should automatically stop when some other songs started playing on the device by the user. How to get notified that some other audio has started playing on the device in my app? Please advise.
UPDATED:
I tried this code, it works for the first time. I.e, when I launch my app and play an audio in my app, my app is playing an audio. Then, When I open some music player and play some other audio there, My app detects notification in "AUDIOFOCUS_LOSS". I am stopping my audio here. Then when again play audio in my app, and then coming back to music player and play some other audio there, this time my app doesn't get detected for this notification, so I couldn't do stop again my audio. This is my issue now.
Could someone help me to solve this please?
public class MyActivity extends ActionBarActivity implements OnCompletionListener, OnPreparedListener, OnErrorListener, OnBufferingUpdateListener, AudioManager.OnAudioFocusChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hclsquad_fm);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
#Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
Toast.makeText(MyActivity.this, "Focus GAINED", Toast.LENGTH_LONG).show();
break;
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Toast.makeText(MyActivity.this, "Focus LOSS", Toast.LENGTH_LONG).show();
if(mediaPlayer != null)
killMediaPlayer();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Toast.makeText(MyActivity.this, "Focus LOSS TRANSIENT", Toast.LENGTH_LONG).show();
break;
default:
}
}
Try this code below. I found this answer here
OnAudioFocusChangeListener listener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
// Lower the volume
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Raise it back to normal
}
}
};
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
int request = am.requestAudioFocus(listener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
Responsible apps will always get audio focus before playing audio. I don't think it is possible for you to detect when another app plays audio if it does not request audio focus.
Instead of requesting audio focus in your onCreate, do it before you start to play audio:
private void play(){
requestAudioFocus();
}
You are loosing audio focus. You should call
requestAudioFocus();
to get control back.

Stop MediaPlayer when an other app play music

In my app, I have a media player which play a stream music:
globalVariable.setPlaying(true);
final ProgressDialog mProgressDialog;
mProgressDialog = ProgressDialog.show(MainActivity.this, "Chargement en cours", "La musique est en train de charger", true);
String url = "http://178.32.181.86:18000";
globalVariable.mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
globalVariable.mp.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
globalVariable.mp.prepareAsync();
globalVariable.mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
bouton.setImageResource(R.drawable.pause);
mProgressDialog.hide();
}
});
It works very fine. When I open another app in front of mine, player continues, and it's great. But if I launch another player (like GooglePlayMusic or youtube), my app doesn't stop music and I have two sounds in the same time.
So I want that my music stop if another app need to play music.
Thanks a lot
You should use AudioManager service to receive notification whether you receive/lost audio focus (Managing audio focus). I've done similar thing in a project where when my app starts playing, Google Play pause and vice versa. Use the following code where you are controlling your media playback like (activity or service)-
// Add this code in a method
AudioManager am = null;
// Request focus for music stream and pass AudioManager.OnAudioFocusChangeListener
// implementation reference
int result = am.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if(result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
{
// Play
}
// Implements AudioManager.OnAudioFocusChangeListener
#Override
public void onAudioFocusChange(int focusChange)
{
if(focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
{
// Pause
}
else if(focusChange == AudioManager.AUDIOFOCUS_GAIN)
{
// Resume
}
else if(focusChange == AudioManager.AUDIOFOCUS_LOSS)
{
// Stop or pause depending on your need
}
}
AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
{
// do something - or don't
}

What is audio focus in Android class AudioManager?

The AudioManager class has a method abandonAudioFocus() and another method requestAudioFocus(). I wonder what is audio focus? And what happens if an AudioManager object gets the audio focus or lost the audio focus?
Thank you!
It has to do with priority when using the speakers, to prevent playing many things at once or being overridden. If you requestAudioFocus(), you're declaring that you want control. You can then listen with onAudioFocusChange(int focusChange) to see if anything else tries to play a sound. You may forcefully lose focus (like during a phone call) but then you can gain it later. You should abandonAudioFocus() when you're finished.
AudioManager am = (AudioManager)getContext().getSystemService(AUDIO_SERVICE);
AudioManager.OnAudioFocusChangeListener focusChangeListener =
focusChange -> {
};
int result = am.requestAudioFocus(focusChangeListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mp = new android.media.MediaPlayer();
mp.setOnCompletionListener(mediaPlayer -> {
am.abandonAudioFocus(focusChangeListener);
});
mp.setDataSource("/data/data/" + getContext().getPackageName() + "/rasa.wav");
mp.prepare();
mp.start();
}

Categories

Resources