使用存储文件夹播放.mp3 UWP

时间:2018-12-10 12:33:22

标签: c# uwp uwp-xaml

我想做一个小项目。像是带有工作笑话的音板。但是我无法在UWP中播放声音。我发现了:

private async System.Threading.Tasks.Task Button_ClickAsync(object sender, RoutedEventArgs e)
        {

            MediaElement PlayMusic = new MediaElement();
            PlayMusic.AudioCategory = Windows.UI.Xaml.Media.AudioCategory.Media;
            StorageFolder Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            Folder = await Folder.GetFolderAsync("folder");
            StorageFile sf = await Folder.GetFileAsync("song.mp3");
            PlayMusic.SetSource(await sf.OpenAsync(FileAccessMode.Read), sf.ContentType);
            PlayMusic.Play();
        }`

但是我不知道该把声音放在哪里。 我已经尝试过Assets文件夹,但是没有用。 我是新手,对我的英语不好对不起。

1 个答案:

答案 0 :(得分:1)

您可以使用 FileOpenPicker 选择要播放的文件,也可以将文件放在资源文件夹中,并使用uri访问。在下面添加了两个示例代码段

//从文件播放

private async void PlayFromFile(object sender, RoutedEventArgs e)
    {
        //Play from file
        FileOpenPicker openPicker = new FileOpenPicker();
        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.FileTypeFilter.Add(".m4p");
        openPicker.FileTypeFilter.Add(".mp3");
        var sf = await openPicker.PickSingleFileAsync();
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.Source = MediaSource.CreateFromStorageFile(sf);
        mediaPlayer.Play();           
    }

//从资产文件夹播放

 private void PlayFromAssetsFolder(object sender,RoutedEventArgs e)
    {
        //Play from assets folder
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/audio.mp3"));
        mediaPlayer.Play();
    }