SoundPlayer.PlaySync过早停止

时间:2011-01-14 21:43:13

标签: c# soundplayer

1 个答案:

答案 0 :(得分:0)

为了防止其他人遇到同步播放大型wav文件的问题,我写的这个方法使用WMP作为替代:

public static int playSoundWMP(string soundFile, bool synchronous = true)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        wmp.URL = soundFile;
        wmp.controls.play();

        Thread.Yield();

        while (wmp.playState == WMPLib.WMPPlayState.wmppsTransitioning)
        {
            Application.DoEvents();
            Thread.Yield();
        }

        int duration = Convert.ToInt32(wmp.currentMedia.duration * 1000);
        double waitTime = wmp.currentMedia.duration;

        if (synchronous)
        {
            Thread.Sleep(duration);
        }

        long elapsed = sw.ElapsedMilliseconds;
        sw.Stop();
        sw = null;

        return (int) wmp.currentMedia.duration * 1000;
    }

此方法使用WMP播放音频文件而不是SoundPlayer类,因此它可以更可靠地播放更大的wav文件......