Lag when playing simultaneous audio clips with SoundEffect
I'm working on a Windows Phone app and am having the following problem. I have a looped .Wav file for background music which can be toggled on or off. Additional sound effects (e.g. Sound1) can be played on button press. When the background music is off, the sound effects play fine. However, when the background music is on, there is a slight (but very noticeable) lag between button press and sound effect. Is there anything I can do programatically to avoid this? Per the recommendations on the MSDN website http://msdn.microsoft.com/en-us/library/ff431744%28v=vs.92%29.aspx, I setup a dispatcherTimer to call FrameworkDispatcher.Update every 50 ms. However, this does not seem to help too much... I have pasted some of my code below. Is there anything else I can do to get rid of this lag?
public partial class Modules : PhoneApplicationPage
{
static SoundEffectInstance loopedSound = null;
static SoundEffectInstance sound1=null;
double pitchValue = 4.0;
static double pitchAdjust = 0.0;
public Modules()
{
InitializeComponent();
// Timer to simulate the XNA game loop (SoundEffect classes are from the XNA Framework)
DispatcherTimer XnaDispatchTimer = new DispatcherTimer();
XnaDispatchTimer.Interval = TimeSpan.FromMilliseconds(50);
XnaDispatchTimer.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } };
XnaDispatchTimer.Start();
}
private void playButton_Click(object sender, RoutedEventArgs e)
{
if (loopedSound!=null)
loopedSound.Dispose();
SoundEffect sound = SoundEffect.FromStream(Application.GetResourceStream(new Uri(@"BackgroundSound.wav", UriKind.Relative)).Stream);
LoopClip(sound);
}
private void stopButton_Click(object sender, RoutedEventArgs e)
{
loopedSound.Stop();
}
static protected void LoopClip(SoundEffect soundEffect)
{
lo开发者_JAVA技巧opedSound = soundEffect.CreateInstance();
loopedSound.IsLooped = true;
loopedSound.Pitch = (float) pitchAdjust;
loopedSound.Play();
}
static protected void sound1Clip(SoundEffect soundEffect)
{
sound1 = soundEffect.CreateInstance();
sound1.IsLooped = false;
sound1.Play();
}
private void Sound1Button_Click(object sender, RoutedEventArgs e)
{
if (sound1 == null)
{
SoundEffect sound = SoundEffect.FromStream(Application.GetResourceStream(new Uri(@"sound1.wav", UriKind.Relative)).Stream);
sound1Clip(sound);
}
if (sound1 != null)
{
sound1.Play();
}
}
}
}
Pre-load the SoundEffect so you don't get the delay from FromStream(). That's however not very phone-friendly.
精彩评论