[英]MediaElement working within WPF but not within Windows 8.1 App
下面顯示的播放音頻文件的代碼在我的WPF應用程序中可以正常運行。 但是,當我在Windows 8.1應用程序中執行相同的代碼時,沒有任何異常,但也沒有聲音。 有人可以幫忙嗎?
private void myMediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
myMediaElement.Source =
new Uri(@"C:\Users\Soph\Music\Addicted.mp3", UriKind.Absolute);
myMediaElement.Play();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
myMediaElement_MediaOpened(sender,e);
}
編輯:
我已根據建議添加了mediaFailed事件(來自http://msdn.microsoft.com/zh-cn/library/windows/apps/windows.ui.xaml.controls.mediaelement.mediafailed )
private string GetHresultFromErrorMessage(ExceptionRoutedEventArgs e)
{
String hr = String.Empty;
String token = "HRESULT - ";
const int hrLength = 10; // eg "0xFFFFFFFF"
int tokenPos = e.ErrorMessage.IndexOf(token, StringComparison.Ordinal);
if (tokenPos != -1)
{
hr = e.ErrorMessage.Substring(tokenPos + token.Length, hrLength);
}
return hr;
}
private void mycontrol_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
// get HRESULT from event args
string hr = GetHresultFromErrorMessage(e);
// Handle media failed event appropriately
}
然后我嘗試調試此:
名稱值類型
此{PracMEWindowsApp.MainPage} PracMEWindowsApp.MainPage e {Windows.UI.Xaml.ExceptionRoutedEventArgs} Windows.UI.Xaml.ExceptionRoutedEventArgs hr“ 0x80070003”字符串令牌“ HRESULT-”字符串tokenPos 40 int hrLength 10 int
這個小時捕獲了什么? 為什么我的文件沒有播放?
要訪問音樂庫,請在應用清單中指定“音樂庫”功能。 始終處理MediaFailed事件也是一個好習慣。
HRESULT 0x80070003是“找不到目錄”。 這表明media元素不喜歡有關文件路徑的內容。 如果收到HRESULT 0x80070005(拒絕訪問),則可能與權限相關。
Windows Store應用程序無權訪問本地文件系統中的文件,它在沙盒環境中運行,並且只能訪問其自己的數據文件夾,無法識別C:\\Users\\Soph\\Music\\Addicted.mp3
這樣的路徑。
有幾種播放媒體文件的方法。
在Package.appxmanifest
指定“音樂庫”功能(這是必需的),然后
private async void btn1_Click(object sender, RoutedEventArgs e)
{
var file = await Windows.Storage.KnownFolders.MusicLibrary.GetFileAsync("Addicted.mp3");
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
myMediaElement.SetSource(stream, file.ContentType);
}
要么
b。 使用FileOpenPicker
,手動選擇歌曲,您可以訪問文件系統中的任何.mp3文件。
private async void btn1_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.FileTypeFilter.Add(".mp3");
openPicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
var file = await openPicker.PickSingleFileAsync();
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
myMediaElement.SetSource(stream, file.ContentType);
}
要么
C。 將Addicted.mp3添加到您的項目,然后
Uri uri = new Uri("ms-appx:///Addicted.mp3");
myMediaElement.Source = uri;
您還可以在XAML中進行設置
<MediaElement x:Name="myMediaElement" Source="Addicted.mp3" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.