首页 > 解决方案 > 为什么 SetSource 不能改变 Source 的值?

问题描述

我将原版Source的设置MediaElementabc.mp3,并且我正在尝试播放另一个本地 mp3,例如D://xxx.mp3.

使用的时候SetSource发现原来的值Source还是原来的abc.mp3,但是音乐居然变成了xxx.mp3

我可以使用player.Source = "D://xxx.mp3";吗?

这是我的代码:

//player is a MediaElement.

private async void Button_Click(object sender, RoutedEventArgs e)
{
    await SetLocalMedia();
}

async private System.Threading.Tasks.Task SetLocalMedia()
{
    var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

    openPicker.FileTypeFilter.Add(".wmv");
    openPicker.FileTypeFilter.Add(".mp4");
    openPicker.FileTypeFilter.Add(".wma");
    openPicker.FileTypeFilter.Add(".mp3");

    var file = await openPicker.PickSingleFileAsync();
    if (file != null)
    {
        var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
        Debug.WriteLine(player.Source);
        player.SetSource(stream, file.ContentType);
        Debug.WriteLine(player.Source);//The output of these tow Debug are same
    }
}

标签: c#xamluwp

解决方案


为什么 SetSource 不能改变 Source 的值?

感谢您花时间报告此问题,问题是如果您SetSource 使用本地文件打开流调用设置媒体源的方法,那么该Source属性将不包含值,这是设计使然。

我可以使用 player.Source = "D://xxx.mp3"; ?

Source属性为 Uri 类型,支持 http 和 UWP本地 uri 方案,如果文件存储在 D 盘,则不能设置player.Source = "D://xxx.mp3(文件方案)。如果您确实想使用 uri 值设置源,我建议将文件复制到应用程序的本地文件夹,然后使用 UWP 本地文件 uri 方案。但这会导致应用的本地存储变大。

private async void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
    var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

    openPicker.FileTypeFilter.Add(".wmv");
    openPicker.FileTypeFilter.Add(".mp4");
    openPicker.FileTypeFilter.Add(".wma");
    openPicker.FileTypeFilter.Add(".mp3");

    var file = await openPicker.PickSingleFileAsync();
    if (file != null)
    {
        await file.CopyAsync(ApplicationData.Current.LocalFolder, file.Name, NameCollisionOption.ReplaceExisting);
        var path = ApplicationData.Current.LocalFolder.Path;
        var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
        Debug.WriteLine(player.Source);
        player.Source = new Uri($"ms-appdata:///local/{file.Name}");
        Debug.WriteLine(player.Source);//The output of these tow Debug are same
    }

    player.Play();
}

推荐阅读