使用声音效果播放同步音频剪辑时滞后

时间:2011-04-23 20:29:57

标签: c# windows windows-phone-7 xna

我正在使用Windows Phone应用,遇到以下问题。我有一个用于背景音乐的循环.Wav文件,可以打开或关闭。按下按钮可以播放其他声音效果(例如Sound1)。当背景音乐关闭时,声音效果很好。但是,当背景音乐打开时,按钮按下和声音效果之间会有轻微(但非常明显)的延迟。有什么我可以以编程方式做以避免这种情况吗?根据MSDN网站http://msdn.microsoft.com/en-us/library/ff431744%28v=vs.92%29.aspx上的建议,我设置了一个dispatcherTimer,每50毫秒调用一次FrameworkDispatcher.Update。但是,这似乎没有太多帮助...我已经粘贴了下面的一些代码。我还能做些什么来摆脱这种滞后吗?

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)
    {
        loopedSound = 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();
        }


    }



}

}

1 个答案:

答案 0 :(得分:2)

预加载SoundEffect,这样就不会从FromStream()中获得延迟。然而,这不是电话友好。