2012-10-20 57 views
1

我有這樣的App.xaml.cs奇文件關聯處理錯誤

protected override void OnFileActivated(FileActivatedEventArgs args) 
{ 
    Window.Current.Content = new Frame(); 
    ((Frame)Window.Current.Content).Navigate(typeof(MainPage), args); 
    Window.Current.Activate(); 
} 

MainPage.xaml.cs

protected override async void OnNavigatedTo(NavigationEventArgs e) 
{ 
    FileActivatedEventArgs filesArgs = (FileActivatedEventArgs)e.Parameter; 
    StorageFile file = (StorageFile)filesArgs.Files[0]; 
    mc.SetSource(await file.OpenReadAsync(), file.ContentType); 
    mc.Play(); 
} 

而這MainPage.xaml

<MediaElement x:Name="mc" /> 

現在,我面臨着一個很奇怪的問題。我已將我的應用程序與.MP4文件關聯。每當我打開任何文件,它都不會立即播放。例如。

  1. 我打開a.mp4,它不會播放,我不關閉應用程序。
  2. 我打開b.mp4,它不會播放,我不關閉應用程序。
  3. 然後,我打開a.mp4,它被播放。如果沒有,我會再試一次並播放它。現在,如果我打開任何MP4文件,直到我關閉該應用程序,它纔會毫無問題地播放。

所以,這個變通辦法有時:

protected override async void OnNavigatedTo(NavigationEventArgs e) 
{ 
    FileActivatedEventArgs filesArgs = (FileActivatedEventArgs)e.Parameter; 
    StorageFile file = (StorageFile)filesArgs.Files[0]; 
    StorageFile file2 = (StorageFile)filesArgs.Files[0]; 
    mc.SetSource(await file2.OpenReadAsync(), file2.ContentType); 
    mc.SetSource(await file2.OpenReadAsync(), file2.ContentType); 
    mc.Play(); 
} 

有誰知道爲什麼它也不是沒有解決辦法的工作?

回答

1

如果您在初始化和/或完全加載控件之前設置源並開始播放,看起來好像文件不播放。這就是爲什麼當應用程序已經加載並偶爾會在第一次通話時它會在隨後的調用中工作。我做了一個簡單的應用程序,並設法重現你的問題大多數嘗試(儘管有時它的工作)。

我嘗試了一個簡單的解決方法,在開始播放之前總是等待MediaElement加載,看起來問題已消失 - 我無法在十幾個調用中重現該問題。

這裏是我做了什麼:

MainPage.xaml中:

<MediaElement x:Name="mc" Loaded="mc_Loaded" /> 

MainPage.xaml.cs中

bool loaded = false; 
Task task = new Task(() => {}); 

private void mc_Loaded(object sender, RoutedEventArgs e) 
{ 
    loaded = true; 
    task.Start(); 
} 

protected override async void OnNavigatedTo(NavigationEventArgs e) 
{ 
    FileActivatedEventArgs filesArgs = (FileActivatedEventArgs)e.Parameter; 
    StorageFile file = (StorageFile)filesArgs.Files[0]; 
    if (!loaded) 
     await task; 
    mc.SetSource(await file.OpenReadAsync(), file.ContentType); 
    mc.Play(); 
} 

我真的不喜歡我的解決方案,因爲它唯一的基於在猜測和經驗測試,但我找不到任何文件說明MediaElement準備好之前需要發生什麼。

+0

@Programmer我在Core 2 Duo 6400上測試它。 –

+0

@Programmer如果您通過從放置MediaElement的頁面調用FilePicker,我不認爲同樣的情況可以發生。 'MediaElement'在頁面的加載過程中被加載,當你打開'FilePicker'時頁面已經加載。它可能是一個錯誤,或者至少是一個無法記錄的功能。您可以嘗試在[MSDN論壇](http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp)上發佈該問題,那裏有更多來自微軟的人員。或者甚至可能在[Microsoft Connect](https://connect.microsoft.com/VisualStudio)上。 –

+0

@Programmer你有沒有試過按照建議使用'MediaOpened'事件?它能解決你的問題嗎? –