近期发布
专辑列表

Windows Phone 游戏合集
JQueryElement
IEBrowser
WPXNA

XNA 中 SoundEffect 与 SoundEffectInstance 的区别

如果你希望在 Windows Phone 上创建游戏,那么 XNA 是一个选择。平方会和你一起探讨和学习 Windows Phone 中 XNA 的小知识。

在 XNA 中 SoundEffect 和 SoundEffectInstance 都可以用来播放声音,比如:常见的 wav 波形文件。但是要注意的是无论是 SoundEffect 或者 SoundEffectInstance 都不能播放 mp3 文件,播放 mp3 需要 XNA 中的 Song 类。

共享资源

你可以将声音文件载入到 SoundEffect 类中,你还可以从 SoundEffect 创建新的 SoundEffectInstance。而这些新的 SoundEffectInstance 将共享 SoundEffect 中包含的声音资源。

在 SoundEffect 的生命周期中,他将保持资源。而一旦 SoundEffect 被销毁,也就是意味着他所创建的 SoundEffectInstance 都将失效。

下面的代码中,我们在 LoadConent 方法中载入声音,在 UnloadConent 方法中释放他们。通过 mySound 我们创建了 mySound1 和 mySound2。

 1 private ContentManager contentManager;
 2 private SoundEffect mySound;
 3 private SoundEffectInstance mySound1;
 4 private SoundEffectInstance mySound2;
 5 
 6 protected override void LoadContent ( )
 7 {
 8  // ...
 9  spriteBatch = new SpriteBatch ( GraphicsDevice );
10 
11  if ( null == this.contentManager )
12   this.contentManager = new ContentManager ( Services, "Content" );
13 
14  this.mySound = this.contentManager.Load<SoundEffect> ( @"mysound" );
15  this.mySound1 = this.mySound.CreateInstance ( );
16  this.mySound2 = this.mySound.CreateInstance ( );
17  // ...
18 } 
19 
20 protected override void UnloadContent ( )
21 {
22  // ...
23  this.mySound1.Dispose ( );
24  this.mySound2.Dispose ( );
25  this.mySound.Dispose ( );
26 
27  this.contentManager.Unload ( );
28  // ...
29 } 

如果我们在 Update 方法中释放 mySound,则调用 mySound1 或者 mySound2 的 Play 方法将出现错误。

1 protected override void Update ( GameTime gameTime )
2 {
3  // ...
4 
5  this.mySound.Dispose ( );
6  this.mySound1.Play ( );
7 }

重复播放

不管是 SoundEffect 或者 SoundEffectInstance,如果声音没有播放完毕,那么调用 Play 方法是无效的。如果你在 Update 中一直调用 Play 方法,声音只会在他播放完毕后才会重新播放。

1 protected override void Update ( GameTime gameTime )
2 {
3  // ...
4 
5  this.mySound.Play ( );
6 }

如果你希望在声音没有播放完成时,重复播放他,那么你可以定义多个 SoundEffectInstance。

播放声音总数

在 Windows Phone 中,XNA 同时播放的声音总数为 16 个。

停止播放

由于 SoundEffect 一般只是播放较小的声音文件,所以一般情况下,是不会停止播放声音的。但如果有时你在循环播放,可能就要用到 Stop 方法。而要停止声音需要通过 SoundEffectInstance 类。

 1 protected override void Update ( GameTime gameTime )
 2 {
 3  // ...
 4 
 5  int seconds = ( int ) gameTime.TotalGameTime.TotalSeconds;
 6 
 7  if ( seconds > 5 )
 8  {
 9   if ( this.mySound1.State != SoundState.Stopped )
10    this.mySound1.Stop ( );
11  }
12  else
13  if ( this.mySound1.State == SoundState.Stopped )
14  {
15   this.mySound1.IsLooped = true;
16   this.mySound1.Play ( );
17   }
18 }

完,与平方一起探索 XNA,体验编程非凡乐趣,更多内容请浏览开发者,转载请注明出处:http://www.wpgame.info/post/decc4_55223b

posted @ 2013-04-14 15:38  麦丝平方  阅读(1193)  评论(0编辑  收藏  举报