在一些应用程序.尤其在触摸屏和休闲游戏中,当用户在应用程序中做出操作同时也播放出对应动作声音.例如现在Silverlight中和WP7已经实现FPS动作类游戏中射击AK-47突击步枪时枪声效果.或是动画操作中飞机起飞动作时伴随的环绕音效.这在用户体验操作时非常重要一环.
想想以前Silverlight版本中实现这种动作音效.开发人员往往采用各种各样技巧尽可能的在为客户提供在低延迟情况下提供完整用来MediaElements元素缓存区预加载音效文件效果.其实现在Windows phone 7XNA游戏开发平台已经为开发人员提供处理声音效果的SoundEffect类支持.同样在Silverlight 5版本添加SoundEffect类做音效处理.
在演示这个Demo前首先可以去下载相关的音效文件[WAV格式]:
WAV Free File DownLoad Link:http://www.wyomingwebdesign.com/files/pages/free_sound_files.html
free_sound_files_Downlaod Link[fllow]
建立一个标准的Silverlight Application:
ok.下载一个飞机起降环绕音的WAV文件.页面通过一个Button按钮点击事件事件驱动的方式播放文件:
1: <Grid x:Name="LayoutRoot" Background="White">
2: <Button Content="Gun Fight_Sound"
3: Height="36"
4: HorizontalAlignment="Left"
5: Margin="107,129,0,0"
6: Name="ClickMe"
7: VerticalAlignment="Top"
8: Width="153"
9: Click="ClickMe_Click" />
10: </Grid>
首先在执行播放文件前.通过Application对象的GetResourceStream()方法来预加载音效文件.通过SoundEffect类FromStream方法把文件流作为转化为可设置播放的对象SoundEffect.首先引入命名空间:
1: using Microsoft.Xna.Framework.Audio;
2: using System.Windows.Resources;
3: using System.Windows.Threading;
Button点击事件操作文件播放 在页面执行加载时加载环绕背景音效:
1: var engineStream =
2: Application.GetResourceStream(new Uri("engine_rumble4.wav", UriKind.RelativeOrAbsolute));
3: _engineEffect = SoundEffect.FromStream(engineStream.Stream);
4:
5: SoundEffectInstance engineInstance = _engineEffect.CreateInstance();
6: engineInstance.IsLooped = true;
7: engineInstance.Pitch = -1.0f; // low sound
8: engineInstance.Volume = 0.75f;
9: engineInstance.Play();
通过SoundEffect对象创建SoundEffectInstance对象.islooped设置是否循环播放. Volume则设置播放音量. Play()方法则执行播放.加载好背景环绕效果音效.但我们点击Button按钮触发射击音效:
1: private void ClickMe_Click(object sender, RoutedEventArgs e)
2: {
3: var laserStream =
4: Application.GetResourceStream(new Uri("laser_shot.wav", UriKind.RelativeOrAbsolute));
5: _laserShotEffect = SoundEffect.FromStream(laserStream.Stream);
6:
7: SoundEffectInstance instance = _laserShotEffect.CreateInstance();
8: instance.Pitch = 1.0f; // high sound
9: instance.Play();
10: }
当然在在游戏场景背景音效需要长期循环渲染.设置在加载页面把背景音效设置循环播放状态:
1: DispatcherTimer timer = new DispatcherTimer();
2: timer.Interval = TimeSpan.FromSeconds(1);
3: //循环播放控制
4: timer.Tick += (s, ea) =>
5: {
6: timer.Stop();
7: SoundEffectInstance engineInstance2 = _engineEffect.CreateInstance();
8: engineInstance2.IsLooped = true;
9: engineInstance2.Pitch = -.75f; // slightly higher sound
10: engineInstance2.Volume = 0.5f;
11: engineInstance2.Play();
12: };
13:
14: timer.Start();
ok.至此当运行界面后首先听到是场景的渲染音效.点击Button按钮将触发射击音效. 界面截图:
有了SoundEffect相对以前Silverlight版本不再需要在费过大力气实现同样的效果/.新的API增加即将大大简化解决问题整个问题流程.Silverlight 5 中支持将逐步的得到完善.源码下载:
SoundEffect Class for Low-latency DownLink:/Files/chenkai/Futures_Sound_Effects_Source.rar