可以使用MediaElement的Source属性来播放内容吗?

本文关键字:播放 属性 MediaElement Source 可以使 | 更新日期: 2023-09-27 18:07:19

我正在尝试通过使用歌曲的目录路径从本地机器播放歌曲。

MediaElement.Source = new Uri(@"D:'Music'Artist'Album'Song.mp3", UriKind.Absolute);

这是可能的工作还是Windows 8应用程序只能使用像mss-appx:这样的URI方案来访问包数据?

当我尝试运行代码时,我得到一条关于MediaElement控件"无效源"的消息

可以使用MediaElement的Source属性来播放内容吗?

Windows Store应用程序没有完全访问文件系统的权限。他们只能(通过路径)直接访问有限的位置(即他们的install和applicationdata文件夹)。

MediaElement可以从它可以直接访问的路径中加载项,但这通常不是有用的,因为这些位置有uri (ms-appx:和ms-appdata:),无论实际路径是什么,它们都会瞄准正确的位置。

歌曲通常在音乐库中,MediaElement不能直接访问。它可以通过MusicLibrary功能获得代理访问,但不允许通过路径访问。应用程序需要通过KnownFolders对象访问该文件:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    StorageFolder musicLib = Windows.Storage.KnownFolders.MusicLibrary;
    StorageFile song = await musicLib.GetFileAsync(@"Artist'Album'Song.mp3");
    var stream = await song.OpenReadAsync();
    me.SetSource(stream, stream.ContentType);
}

如果歌曲不在功能允许的库中,则用户需要通过FolderPicker或诸如此类的工具授予权限。用户可以选择音乐位置的根目录,应用程序可以用Windows.Storage.AccessCache类缓存,这样用户就不需要多次选择文件夹或单独选择文件。

我将在我的博客文章中详细讨论这个问题:跳过路径:坚持使用StorageFile

您需要使用文件打开选择器来选择D盘中的文件。

    FileOpenPicker openPicker = new FileOpenPicker();
    openPicker.ViewMode = PickerViewMode.Thumbnail;
    openPicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
    openPicker.FileTypeFilter.Add(".mp3");
    StorageFile file = await openPicker.PickSingleFileAsync();
    IRandomAccessStreamWithContentType content = await file.OpenReadAsync();
    Debug.WriteLine("Content Type: " + content.ContentType);
    player.SetSource(content, content.ContentType);

这个链接有答案(如果你可以使用应用程序文件夹)

MediaElement.Source = new Uri("ms-appx-web:///Assets/Song.mp3", UriKind.Absolute);