kalitsov
kalitsov

Reputation: 1639

How to play a system sound in Xamarin.Forms

I'm looking for lightweight built in system cross platform sound player. Something that could beep like System.Console.Beep and which i could invoke directly from my view model.

I'm aware that i could use a provider (strategy) pattern to coin the platform specific implementations or to use some media player like XamarinMediaManager.

Upvotes: 3

Views: 4145

Answers (1)

G.Mich
G.Mich

Reputation: 1666

You can use Dependency service

ANDROID

public class AudioService : IAudio
{

    private MediaPlayer _mediaPlayer;

    public bool PlayFile()
    {
        _mediaPlayer = MediaPlayer.Create(global::Android.App.Application.Context, Resource.Raw.test);
        _mediaPlayer.Start();

        return true;
    }

}

IOS

public class AudioService : IAudio
{

private AVAudioPlayer _ringtoneAudioPlayer;
public AudioService()
{
    _ringtoneAudioPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename("call.caf"));
    _ringtoneAudioPlayer.NumberOfLoops = -1; // infinite
}

public void PlayFile()
{
    if (_ringtoneAudioPlayer != null)
    {
        _ringtoneAudioPlayer.Stop();
    }
    _ringtoneAudioPlayer.Play();
}
} 

UWP

public class AudioService : IAudio
{

    public async Task PlayAudioUWP(string fileName)
    {
        StorageFolder Folder = await Package.Current.InstalledLocation.GetFolderAsync("Assets");
        StorageFile sf = await Folder.GetFileAsync(fileName);
        var PlayMusic = new MediaElement();
        PlayMusic.AudioCategory = Windows.UI.Xaml.Media.AudioCategory.Media;
        PlayMusic.SetSource(await sf.OpenAsync(FileAccessMode.Read), sf.ContentType);
        PlayMusic.Play();
    }

}

If you want you can try and this plugin

https://www.nuget.org/packages/XamarinAudioManager/

Upvotes: 1

Related Questions