AxWindowsMediaPlayer剪辑有时不会播放

时间:2013-03-18 15:17:57

标签: c# .net windows media-player

我有一个简单的单线程Windows窗体.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);
    }

有人可以建议解决这个问题吗?也许我不应该删除方法末尾的文件?但是临时文件会堆积起来......

我在Windows 7上...

2 个答案:

答案 0 :(得分:1)

我猜这个文件被删除的速度比它可以播放的速度快。

您可以尝试使用File.Delete(tempFile);使用PlayStateChange事件

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

如果长时间保持玩家对象,则可能需要取消订阅该事件。

答案 1 :(得分:0)

似乎我解决了这个问题......事实上,删除文件导致了这个......

溶液:

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