MediaElement.SetSource崩溃了应用程序

时间:2012-05-13 13:37:56

标签: c# windows xaml windows-8 windows-runtime

我正在开发适用于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");
    }
}

1 个答案:

答案 0 :(得分:0)

修正了它。原来是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();
    }
}
相关问题