AxWindowsMediaPlayer剪辑有时不播放

本文关键字:播放 AxWindowsMediaPlayer | 更新日期: 2023-09-27 18:04:25

我有一个简单的单线程windows forms . net 4.5应用程序,用户听口头单词(wav文件),然后选择代表单词的正确图片。

问题是片段有时会(非常罕见-大约1%的时间,完全随机)不播放…

这是播放剪辑的方法:

    public static void PlayWordAudio(Word word, AxWMPLib.AxWindowsMediaPlayer player)
    {
        string tempFile = Path.GetTempFileName() + ".wav";
        MemoryStream stream = new MemoryStream(word.Audio);
        using (Stream fileStream = File.OpenWrite(tempFile))
        {
            stream.WriteTo(fileStream);
        }
        player.URL = tempFile;
        File.Delete(tempFile);
    }
谁能建议一个解决这个问题的方法?也许我不应该在方法结束时删除文件?但是临时文件会堆积起来…

AxWindowsMediaPlayer剪辑有时不播放

我猜文件被删除的速度比播放的速度快。

你可以尝试使用PlayStateChange事件来代替File.Delete(tempFile);

player.PlayStateChange += (snd, psce) => {
     switch (psce.newState)
    {
        case 1:    // Stopped (maybe use 12 =>  Last )
            File.Delete(tempFile);
            break;
        default:
            Debug.WriteLine(psce.newState);
            break;
    }
};

如果你长时间保留播放器对象,你可能需要取消订阅事件

看来我解决了这个问题…实际上是删除文件导致的…

解决方案:

public static void PlayWordAudio(Word word, AxWMPLib.AxWindowsMediaPlayer player)
    {
        string tempFile = Path.GetTempFileName() + ".wav";
        MemoryStream stream = new MemoryStream(word.Audio);
        using (Stream fileStream = File.OpenWrite(tempFile))
        {
            stream.WriteTo(fileStream);
        }
        player.URL = tempFile;
        RunDelayed(5000, File.Delete, tempFile); //if we delete file immediately then clip sometimes would not be played
    }        
    public delegate void DelayedFuncion(string param);
    public static void RunDelayed(int delay, DelayedFuncion function, string param = null)
    {
        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        DelayedArgs args = new DelayedArgs() { delayedFunction = function, param = param };
        timer.Tag = args;
        timer.Tick += TimerElapsed;            
        timer.Interval = delay;
        timer.Start();
    }
    private static void TimerElapsed(object sender, EventArgs e)
    {
        System.Windows.Forms.Timer timer = sender as System.Windows.Forms.Timer;
        timer.Stop();
        DelayedArgs args = timer.Tag as DelayedArgs;
        args.delayedFunction(args.param);
    }

    class DelayedArgs
{
    public Util.DelayedFuncion delayedFunction;
    public string param;
}