Windows Phone 播放音频之SoundEffect

  前面介绍了Windows Phone 录制音频Windows Phone 保存录音录制的音频保存为WAV格式。在Windows Phone中播放音频的方式有很多种,下面就介绍一种专一用于播放WAV格式的播放方式。需要用到SoundEffectSoundEffectInstance两个类,这两个类属于 XNA Framework ,所以需要添加引用 Microsoft.Xna.Framework。
  1.同录制音频一样需要透过指定一个定期执行 FrameworkDispatcher.Update() 的事件。  

        //设置定时器
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(33);
timer.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } };
timer.Start();

  2.获取WAV文件流,用于创建SoundEffect对象。

        //获取WAV文件流
Stream stream = null;
//如果是资源文件处理
StreamResourceInfo info = Application.GetResourceStream(new Uri(path, UriKind.Relative));
if (info != null)
{
stream = info.Stream;
}
//如果是独立存储文件处理
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
//打开文件
stream = myIsolatedStorage.OpenFile(path, FileMode.Open, FileAccess.Read);
}

  3.创建SoundEffect对象,播放音频。

        //创建音频播放实例
SoundEffect sound = SoundEffect.FromStream(stream);
SoundEffectInstance soundInstance = sound.CreateInstance();
//设置循环播放
soundInstance.IsLooped = true;
//启动播放
soundInstance.Play();

  4.音频暂停,复位,停止。

        //暂停
soundInstance.Pause();
//复位
soundInstance.Resume();
//停止
soundInstance.Stop();

  5.设置音频播放的音量。

        //音量取值范围为[0,1],默认值为0.85
soundInstance.Volume = 0.5F;

  使用SoundEffect和SoundEffectInstance方式只能播放WAV格式的音频,并且还需要引入XNA库。

posted @ 2012-03-12 12:33  宇之乐  阅读(1968)  评论(0编辑  收藏  举报