SoundEffect类Windows Phone 8中的循环声音

时间:2014-02-27 13:48:37

标签: c# windows-phone-8 xna

我正在开发一款游戏,需要为此添加背景音乐。我尝试了Microsoft.Xna.Framework.Audio命名空间的SoundEffect类。

最初我用过

SoundEffectInstance Sound = 
     SoundEffect.FromStream(Application.GetResourceStream(new Uri("Assets/background.wav", UriKind.Relative)).Stream).CreateInstance();
Sound.IsLooped = true;
Sound.Play();

它没有用。然后我试了

SoundEffect sound;
StreamResourceInfo info = Application.GetResourceStream(
            new Uri("Assets/background.wav", UriKind.Relative));
sound= SoundEffect.FromStream(info.Stream);
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
sound.Play();

它的工作。但是Cant循环播放音乐。 任何人都可以请描述我的差异,并提出一种循环音乐的方法。

编辑:我想称之为'public MainPage(){}

更新:我通过在代理中添加以下内容使其成功

public MainPage()
{
  InitializeComponent();
  startBackgroundMusic();
}

private void startBackgroundMusic()
{
  this.Dispatcher.BeginInvoke(() =>
  {
    StreamResourceInfo info = Application.GetResourceStream(
      new Uri("Assets/background.wav", UriKind.Relative));
    backgroundMusic = SoundEffect.FromStream(info.Stream);
    SoundEffectInstance instance = backgroundMusic.CreateInstance();
    instance.IsLooped = true;
    instance.Play();

  });
} 

现在我有另一个问题,音频文件的持续时间是2分钟,但上面的代码只播放音乐30秒。如何克服这个问题。

1 个答案:

答案 0 :(得分:0)

你快到了。 SoundEffect类确实不支持循环。因此,您需要SoundEffectInstance类。您可以根据已创建的SoundEffect实例创建此类的实例:

//What you already had:
StreamResourceInfo info = Application.GetResourceStream(new Uri("Assets/background.wav", UriKind.Relative));
SoundEffect sound = SoundEffect.FromStream(info.Stream);

//Here's the magic:
SoundEffectInstance instance = sound.CreateInstance();
instance.IsLooped = true;
instance.Play();

更多阅读(MSDN)