1

我有一个简单的单线程 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...

4

2 回答 2

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

如果您将播放器对象保留很长时间,您可能必须取消订阅该事件。

于 2013-03-18T17:04:00.193 回答
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;
}
于 2013-03-18T17:25:50.697 回答