Hello,
Welcome to our Microsoft Q&A platform!
Android and iOS native provide the related method, try to select the speaker on each native platform and then using DependencyService to call the code in the shared project. Here is the sample code, you could refer to it.
Android platform:
public class DroidAudioService : IAudioService
{
Context context;
public AudioService()
{
context = Android.App.Application.Context;
}
public void PlayUsingEarSpeaker()
{
var mediaPlayer = MediaPlayer.Create(Android.App.Application.Context, Resource.Raw.sound_file);
var audioManager = (AudioManager)Android.App.Application.Context.GetSystemService(Context.AudioService);
mediaPlayer.SetAudioStreamType(Android.Media.Stream.VoiceCall);
audioManager.Mode = Mode.InCall;
audioManager.SpeakerphoneOn = false;
mediaPlayer.Start();
}
public void PlayUsingSpeaker()
{
var mediaPlayer = MediaPlayer.Create(Android.App.Application.Context, Resource.Raw.sound_file);
var audioManager = (AudioManager)Android.App.Application.Context.GetSystemService(Context.AudioService);
mediaPlayer.SetAudioStreamType(Android.Media.Stream.Music);
audioManager.Mode = Mode.Normal;
audioManager.SpeakerphoneOn = true;
mediaPlayer.Start();
}
}
iOS platform:
public class IOSAudioService : IAudioService
{
public AudioService()
{
}
public void PlayUsingEarSpeaker(string fileName)
{
var session = AVAudioSession.SharedInstance();
session.SetCategory(AVAudioSessionCategory.PlayAndRecord);
session.SetActive(true);
NSError error;
var player = new AVAudioPlayer(new NSUrl(fileName), "mp3", out error);
player.Volume = 1.0f;
player.Play();
}
public void PlayUsingSpeaker(string fileName)
{
var session = AVAudioSession.SharedInstance();
session.SetCategory(AVAudioSessionCategory.Playback);
session.SetActive(true);
NSError error;
var player = new AVAudioPlayer(new NSUrl(fileName), "mp3", out error);
player.Volume = 1.0f;
player.Play();
}
}
Best Regards,
Jarvan 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.