How to stop playing music when the smartphone application starts (iOS/Android)

Asked 2 years ago, Updated 2 years ago, 73 views

You can stop playing music when you start the smartphone application, but
We are thinking of implementing this in Xamarin(C#).
I'm looking for an example implementation, but I can't find it.

If you know, please let me know.

ios android c# xamarin

2022-09-30 21:17

1 Answers

The standard music app can be controlled by MPMusicPlayerController.iPodMusicPlayer.

var player=MediaPlayer.MPMusicPlayerController.iPodMusicPlayer;
if(player.PlaybackState==MediaPlayer.MPMusicPlaybackState.Playing)
{
    player.Pause();
}

If it is not limited to music apps, you can do it with AVFoundation.AVAudioSession.

 var session=AVFoundation.AVAudioSession.SharedInstance();
NSError error;
session.SetActive(true, outerr);

AVAudioSession gives you more control, such as "Turn down the volume of other apps and play your app's voice."

For Android, AudioManager.RequestAudioFocus can stop playing other apps by taking away audio focus exclusively.

The following example takes the focus away when the app screen appears, stops playing other apps, and gives up when the app is in the background.

public class MainActivity: Activity, Android.Media.AudioManager.IonAudioFocusChangeListener
{
    Android.Media.AudioManager_audioManager;

    protected override void OnResume()
    {
        base.OnResume();

        _audioManager= (Android.Media.AudioManager) GetSystemService (Context.AudioService);

        // exclusively deprive someone of focus
        _audioManager.RequestAudioFocus(this, Android.Media.Stream.Music, Android.Media.AudioFocus.GainTransientExclusive);
    }

    public void OnAudioFocusChange([GeneratedEnum] Android.Media.AudioFocus FocusChange)
    {
       // be called when one gets focus
    }

    protected override void OnPause()
    {
        // relinquish focus
        _audioManager.AbandonAudioFocus(this);
        base.OnPause();
    }
}

Audio-related controls are complicated and difficult for each platform, so you should first learn about each Android/iOS API.


2022-09-30 21:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.