播放.mp3 UWP和存储文件夹

我想做一个小项目 . 像工作中的笑话的音板 . 但我不能在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)

2 years ago

您可以使用 FileOpenPicker 选择要播放的文件,也可以将文件放在assets文件夹中并使用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();
    }