简体   繁体   English

Xamarin SimpleAudioPlayer 返回 System.NullReferenceException

[英]Xamarin SimpleAudioPlayer returns System.NullReferenceException

I am trying to play a .wav file in Xamarin.我正在尝试在 Xamarin 中播放 .wav 文件。

The file is found but I get the below execption using this code.该文件已找到,但我使用此代码得到以下执行。 How is that possible as it does find the emailalert.wav file and should get a stream?这怎么可能,因为它确实找到了 emailalert.wav 文件并且应该得到一个流?
System.NullReferenceException: Object reference not set to an instance of an object. System.NullReferenceException:未将对象引用设置为对象的实例。

Happens on this line:发生在这一行:

 audio.Load(stream);

 public void Play() { String path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); String filename2 = "Folder1/emailalert.wav"; String filenameB = Path.Combine(path, filename2); if (File.Exists(filenameB)) { var stream = GetStreamFromFile(filenameB); var audio = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current; audio.Load(stream); audio.Play(); } }

I found a solution to embedd the file directly under the Resources folder and then using this code.我找到了一个解决方案,将文件直接嵌入到 Resources 文件夹下,然后使用此代码。 I also in the Properties of the .wav file choosed "Build Action" and "Embedded Resource".我还在 .wav 文件的属性中选择了“构建操作”和“嵌入式资源”。

Now this code plays the file nicely:现在这段代码可以很好地播放文件:

 public void Play() { System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); string[] resources = assembly.GetManifestResourceNames(); foreach (string resource in resources) { if (resource.Contains("emailalert.wav")) { Stream stream = assembly.GetManifestResourceStream(resource); if (stream != null) { var audio = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current; audio.Load(stream); audio.Play(); break; } } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM