如何以Xamarin形式播放音频? [英] How to play audio in xamarin forms?
问题描述
我正在尝试播放本地存储的音频文件.我正在使用 Xam.Plugin.SimpleAudioPlayer
播放音频.对于UWP和Android,分别在Assets文件夹中添加文件,并将Build Action分别设置为Content和Android Asset.
I am trying to play an audio file which is stored locally. I am using Xam.Plugin.SimpleAudioPlayer
for playing audio. For UWP and Android, added the files in the Assets folder with the Build Action set to Content and Android Asset respectively.
我的代码:
private void PlayAudio()
{
try
{
var stream = GetStreamFromFile("audio.mp3");
var audio = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
audio.Load(stream);
audio.Play();
}
catch (Exception e)
{
Debug.WriteLine("exception:>>" + e);
}
}
Stream GetStreamFromFile(string filename)
{
var assembly = typeof(App).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream("AudioPlay." + filename);
return stream;
}
但是在android和UWP中出现异常却没有在IOS中签入.
But getting an exception in android and UWP, didn't check in IOS.
Android异常:
Android Exception:
[0:]异常:>> System.NullReferenceException:对象引用未设置为对象的实例.在C:\ dev \ open \ Xamarin-Plugins \ SimpleAudioPlayer \ SimpleAudioPlayer \ Plugin.SimpleAudioPlayer.Android \ SimpleAudioPlayerImplementation.cs:100中的Plugin.SimpleAudioPlayer.SimpleAudioPlayerImplementation.Load(System.IO.Stream audioStream)[0x00050]处在F:\ AudioPlay \ AudioPlay \ AudioPlay \ MainPage.xaml.cs:63的AudioPlay.MainPage.PlayAudio()[0x00014]
[0:] exception:>>System.NullReferenceException: Object reference not set to an instance of an object. at Plugin.SimpleAudioPlayer.SimpleAudioPlayerImplementation.Load (System.IO.Stream audioStream) [0x00050] in C:\dev\open\Xamarin-Plugins\SimpleAudioPlayer\SimpleAudioPlayer\Plugin.SimpleAudioPlayer.Android\SimpleAudioPlayerImplementation.cs:100 at AudioPlay.MainPage.PlayAudio () [0x00014] in F:\AudioPlay\AudioPlay\AudioPlay\MainPage.xaml.cs:63
我正在使用.mp3文件.我在此实现中缺少什么吗?请帮助我解决此问题?
I am using .mp3 file. Am I missing something in this implementation? Please help me to fix this issue?
推荐答案
您只需要将mp3文件直接放在共享项目中即可.并调用方法
You just need to directly put the mp3 file in share project . And call the method
var stream = GetStreamFromFile("xxx.mp3");
var audio = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
audio.Load(stream );
audio.Play();
Stream GetStreamFromFile(string filename)
{
var assembly = typeof(App).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream("yourprojectname." + filename);
return stream;
}
更新
我检查了您的演示,以及是否要在项目中播放mp3文件.您需要将mp3的构建操作设置为嵌入式资源
右键单击mp3文件->属性
Right click the mp3 file -> Property
这篇关于如何以Xamarin形式播放音频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!