如何在Xamarin.Forms中播放系统声音

时间:2017-04-03 13:01:27

标签: xamarin xamarin.forms

我正在寻找轻量级内置系统跨平台声音播放器。可以像System.Console.Beep那样发出哔哔声的东西,我可以直接从我的视图模型中调用它。

我知道我可以使用提供商(策略)模式来推广特定于平台的实现,或使用像XamarinMediaManager这样的媒体播放器。

1 个答案:

答案 0 :(得分:1)

您可以使用依赖关系服务

<强>机器人

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();
    }

}

如果你想要,你可以试试这个插件

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