我正在使用Xamarin.forms为Android,iOS和Windows Phone创建一个应用程序.我的问题是如何使用Xamarin Forms播放mp3或wav?
我的业务逻辑由共享项目处理,我不知道如何使用特定平台"MediaPlayer".
现在Xamarin.form s没有声音API,所以你需要使用DependencyService
检查以下链接,它对我来说工作正常:
https://www.codeproject.com/Articles/1088094/Playing-audio-mp-File-in-Xamarin-Forms
我们需要创建一个将在平台特定项目中实现的接口,我将其命名为IAudio.cs,其代码如下:
using System; namespace AudioPlayEx { public interface IAudio { void PlayAudioFile(string fileName); } }
Android解决方案:
using System; using Xamarin.Forms; using AudioPlayEx.Droid; using Android.Media; using Android.Content.Res; [assembly: Dependency(typeof(AudioService))] namespace AudioPlayEx.Droid { public class AudioService: IAudio { public AudioService () { } public void PlayAudioFile(string fileName){ var player = new MediaPlayer(); var fd = global::Android.App.Application.Context.Assets.OpenFd(fileName); player.Prepared += (s, e) => { player.Start(); }; player.SetDataSource(fd.FileDescriptor,fd.StartOffset,fd.Length); player.Prepare(); } } }
iOS解决方案:
using System; using Xamarin.Forms; using AudioPlayEx; using AudioPlayEx.iOS; using System.IO; using Foundation; using AVFoundation; [assembly: Dependency (typeof (AudioService))] namespace AudioPlayEx.iOS { public class AudioService : IAudio { public AudioService () { } public void PlayAudioFile(string fileName) { string sFilePath = NSBundle.MainBundle.PathForResource (Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName)); var url = NSUrl.FromString (sFilePath); var _player = AVAudioPlayer.FromUrl(url); _player.FinishedPlaying += (object sender, AVStatusEventArgs e) => { _player = null; }; _player.Play(); } } }
最后,我们将在PCL /共享项目中使用以下代码来播放音频文件.
DependencyService.Get().PlayAudioFile("MySong.mp3");
我刚刚为iOS,Android,UWP,Windows 8.1和Windows Phone 8.1创建了适用于Xamarin的AudioManager.如果您有兴趣,请访问https://github.com/jcphlux/XamarinAudioManager.有一个Nuget包的链接或随意克隆项目.
我认为,Xamarin.Forms目前没有声音API,所以你必须编写自定义的,特定于平台的代码.
检查James Montemagno如何实现TextToSpeech(使用DependencyService)
参考:
Xamarin.Forms中的音频示例:SimpleAudioForms
James Montemagno的TextToSpeech