在WindowsPhone8.1中替换MediaElement中以前用作源代码的文件会引发E_ACCSESSDENIED

本文关键字:文件 ACCSESSDENIED 源代码 替换 WindowsPhone8 MediaElement | 更新日期: 2023-09-27 18:29:20

我想做的是让用户记录他的声音。录音将存储在本地存储器中。用户应该能够播放录音或将其替换为新的。这就是我遇到麻烦的地方。

场景A:还没有录制,这很好。。。当用户按下录制按钮时,会采取这些步骤来录制音频,然后将其设置为媒体元素的源。

// user starts recording by pressing a button 
// create file with replace option
var audioStorageFile = await folder.CreateFileAsync(desiredName, CreationCollisionOption.ReplaceIfExists);                
await mediaCapture.StartRecordToStorageFileAsync(audioEncodingProperties, audioStorageFile); 
// user stops recording...
await mediaCapture.StopRecordAsync(); 
//...
audioStream = await audioStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
MyMediaElement.SetSource(audioStream, audioStorageFile.ContentType);

我可以随心所欲地重复这个过程,并且旧的音频文件总是被新的替换。

场景B:当我导航到页面时,录制已经存在,所以我想立即将其加载到MediaElement(OnNavigatedTo事件),就像这个

var audioStorageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(desiredName);
audioStream = await audioStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
MyMediaElement.SetSource(audioStream, audioStorageFile.ContentType);

所以用户导航到页面,文件已经加载到MediaElement。当用户想要替换旧录制时,问题就开始了。这段代码在场景A的代码之前调用:

MyMediaElement.Stop();
MyMediaElement.Source = null;

当它到达线路时

var audioStorageFile = await folder.CreateFileAsync(desiredName, CreationCollisionOption.ReplaceIfExists);

引发了UnauthorizedAccessException:拒绝访问。(HRESULT中的异常:0x80070005(E_ACCESSDENIED))。很明显,引发异常的原因是我试图替换的文件正在使用中。但我不明白为什么以及如何避免它?有人能认出我做错了什么吗?谢谢

在WindowsPhone8.1中替换MediaElement中以前用作源代码的文件会引发E_ACCSESSDENIED

在创建文件之前添加.Source=null

MyMediaElement.Source = null;
var audioStorageFile = await folder.CreateFileAsync(desiredName, CreationCollisionOption.ReplaceIfExists);                

如果您没有在完成后关闭/处理Streams的习惯。。。你会过得很糟糕。

为了确保dispose被调用,养成使用using 的习惯

MediaElement设置为

var audioStorageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("your_wav.wav");
using(Windows.Storage.Streams.IRandomAccessStream audio = await audioStorageFile.OpenAsync(FileAccessMode.Read))
{
    this.myMed.SetSource(audio, audioStorageFile.ContentType);                
}

使用上述方法,我能够通过"your_wav.wav"进行录制,无论它是否已设置为MediaElement的Source。

好的,事实证明,问题实际上是在将MediaElement添加到可视化树之前,我正在设置MediaElement的源。我将设置媒体源的代码从OnNavigatedTo移动到MediaElement.Loaded事件,问题就解决了。多亏了这个问题,我找到了解决办法。