Windows Phone实用开发技巧(37):创建一个全局播放器
在做windows phone 开发的时候,有时候我们需要在某些页面中进行声音的播放。而播放的方式也有多种:
1. 使用MediaElement
2. 使用SoundEffect
3. 使用后台播放
SoundEffect只能播放wav格式的文件;后台播放可以在程序退出后仍然继续播放;MediaElement适用于大多数情况,但不能实现后台播放,MediaElement依赖页面并且在页面中只有一个实例可以正常工作。
本文讲讲如何在应用中使用MediaElement作为程序全局播放器,并提供一个帮助类。
由于MediaElement依赖于UI,我们不能在ViewModel中创建一个MediaElement实例进行声音的播放,所以我们需要将MediaElement放置在一个UI容器中,下面是帮助类的代码:
public class GlobalPlayer { static Popup popUp; private static MediaElement _player; public static void Play(string filePath) { popUp = new Popup(); _player = new MediaElement(); _player.Source = null; popUp.Child = _player; popUp.IsOpen = true; try { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { using (var stream = new IsolatedStorageFileStream(filePath, FileMode.Open, store)) { _player.SetSource(stream); _player.Volume = 1.0; _player.Play(); _player.MediaEnded += new RoutedEventHandler((sender, e) => { stream.Close(); stream.Dispose(); _player.Source = null; _player = null; }); _player.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>((s, args) => { stream.Close(); stream.Dispose(); _player.Source = null; _player = null; }); } } } catch (Exception) { _player.Source = null; _player = null; } } public static void StopPlay() { if (_player != null && _player.CurrentState == MediaElementState.Playing) { try { _player.Source = null; _player.Stop(); } catch (Exception) { //throw; } } } }
使用方法十分简单,当我们需要在不同的页面播放同一声音的时候,将存储在独立空间的路径传入即可。
Updated 2013-02-28: 我们使用静态构造函数去初始化MediaElement 和PopUp
}
public static void Play(string filePath)
如果您喜欢我的文章,您可以通过支付宝对我进行捐助,您的支持是我最大的动力https://me.alipay.com/alexis
作者:Alexis
出处:http://www.cnblogs.com/alexis/
关于作者:专注于Windows Phone 7、Silverlight、Web前端(jQuery)。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,如有问题,可以通过shuifengxuATgmail.com 联系我,非常感谢。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
2011-09-07 Windows Phone 实用开发技巧(20):ApplicationBar 的Text国际化