Hello,
Welcome to our Microsoft Q&A platform!
In xamarin forms, we don't have the common api to achieve this.But we can try to use DependencyService to call the loacal fuction in seperate plarform(android, ios and uwp ).
In android,
You can use DependencyService
and AudioFocus
to achieve it, when you record the audio, you can create interface in PCL.
public interface IControl
{
void StopBackgroundMusic();
}
When you record the audio, you can executed the DependencyService with following code.
private void Button_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IControl>().StopBackgroundMusic();
//record the audio
}
In android folder, you can create a StopMusicService to achieve that.
[assembly: Dependency(typeof(StopMusicService))]
namespace TTSDemo.Droid
{
public class StopMusicService : IControl
{
AudioManager audioMan;
AudioManager.IOnAudioFocusChangeListener listener;
public void StopBackgroundMusic()
{
audioMan = (AudioManager)Android.App.Application.Context.GetSystemService(Context.AudioService);
listener = new MyAudioListener(this);
var ret = audioMan.RequestAudioFocus(listener, Stream.Music, AudioFocus.Gain);
}
}
internal class MyAudioListener :Java.Lang.Object, AudioManager.IOnAudioFocusChangeListener
{
private StopMusicService stopMusicService;
public MyAudioListener(StopMusicService stopMusicService)
{
this.stopMusicService = stopMusicService;
}
public void OnAudioFocusChange([GeneratedEnum] AudioFocus focusChange)
{
// throw new NotImplementedException();
}
}
}
Refer: https://stackoverflow.com/questions/60461679/pause-background-service-in-xamarin-forms
In additon, we can also try to use MediaBrowserService
to achieve this. When you use a MediaBrowserService
, other components and applications with a MediaBrowser
can discover your service, create their own media controller, connect to your media session, and control the player. This is how Wear OS and Android Auto Applications gain access to your media application.
For more details, you can check document :
https://developer.android.com/guide/topics/media-apps/audio-app/building-an-audio-app
Best Regards,
Jessie Zhang
---
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.