Looping sound in SoundEffect class Windows Phone 8

百般思念 提交于 2019-12-25 08:17:13

问题


I am developing a game, and need to add background music for that. I tried Microsoft.Xna.Framework.Audio namespace's SoundEffect class.

Initially I used

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

And it was not working. Then I tried

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();

And its working. But Cant loop the music. Can anyone please describe me the differences and suggest a way to loop the music please.

Edit : I wanna call this is `public MainPage() { }

Update : I made it work by adding this in delegates as below

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();

  });
} 

Now I have another problem that, the audio file duration is 2mins but the above code plays the music only for 30 seconds. How to overcome this issue.


回答1:


You're almost there. The SoundEffect class does indeed not support looping. Therefore you need the SoundEffectInstance class. You can create an instance of this class based on your already created SoundEffect-instance:

//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();

More reading (MSDN)

  • Playing a Sound
  • Looping a Sound
  • SoundEffect class
  • SoundEffectInstance class


来源:https://stackoverflow.com/questions/22070480/looping-sound-in-soundeffect-class-windows-phone-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!