使用SoundEffect播放同步音频剪辑时出现延迟

本文关键字:延迟 SoundEffect 播放 同步 音频 使用 | 更新日期: 2023-09-27 17:52:16

我正在工作的Windows Phone应用程序,我有以下问题。我有一个循环的。wav文件的背景音乐,可以切换打开或关闭。额外的音效(例如Sound1)可以在按下按钮时播放。当背景音乐关闭时,声音效果很好。然而,当背景音乐打开时,按键和音效之间会有轻微的延迟(但非常明显)。我是否可以通过编程来避免这种情况?根据MSDN网站http://msdn.microsoft.com/en-us/library/ff431744%28v=vs.92%29.aspx上的建议,我设置了dispatcherTimer来调用FrameworkDispatcher。每50毫秒更新一次。然而,这似乎并没有太大帮助……我把我的一些代码粘贴在下面。我还能做些什么来消除这种滞后吗?

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

    }

}

}

使用SoundEffect播放同步音频剪辑时出现延迟

预加载SoundEffect,这样你就不会从FromStream()中获得延迟。然而,这对手机不太友好。