MediaElement.SetSource 导致应用程序崩溃

本文关键字:应用程序 崩溃 SetSource MediaElement | 更新日期: 2023-09-27 18:34:11

我正在开发一个适用于Windows 8的录音机应用程序,并且注意到当我将IRandomAccessStream传递给MediaElement.SetSource时,应用程序崩溃,并且没有抛出Visual Studio可见的异常。我应该如何调试此问题?可能是什么原因造成的?

以下是导致崩溃的代码:

void mediaFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count == 1)
    {
        string fname = e.AddedItems[0] as string;
        Stream fstream = GlobalVariables.encryptedFS.OpenFile(fname);
        MediaElement elem = new MediaElement();
        mainGrid.Children.Add(elem);
        elem.AutoPlay = true;
        elem.SetSource(new WinRTStream(fstream, true), "audio/x-ms-wma");
    }
}

MediaElement.SetSource 导致应用程序崩溃

修复了它。结果证明是我实现IAsyncOperationWithProgress中的一个错误。
对于那些面临类似困难的人,以下是修复它的代码:

class ReadOperation : IAsyncOperationWithProgress<IBuffer, uint>
{
    Stream _underlyingstream;
    IAsyncAction _task;
    IBuffer val;
    byte[] _buffer;
    int bytesread;
    public ReadOperation(Stream str, IBuffer buffer, uint cnt)
    {
        uint count = cnt;
        _underlyingstream = str;
        if (_underlyingstream.Length - _underlyingstream.Position < count)
        {
            _buffer = new byte[_underlyingstream.Length - _underlyingstream.Position];
            count = (uint)_buffer.Length;
        }
        _buffer = new byte[count];
        val = buffer;
        _task = Task.Run(async delegate()
        {
            while (bytesread < count)
            {
                int cout = await str.ReadAsync(_buffer, bytesread, (int)count);
                if (cout == 0)
                {
                    break;
                }
                bytesread += cout;
            }
        }).AsAsyncAction();
    }
}