【问题标题】:Windows Phone 8.1 Music on click eventWindows Phone 8.1 音乐点击事件
【发布时间】:2015-09-16 05:03:52
【问题描述】:

我目前正在尝试单击按钮时播放 mp3 文件,我正在尝试像他一样使用该功能:How can I play mp3 files stored in my Windows Phone 8.1 solution? 但它运行得不好,它说

Error   1   The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.    c:\users\halt\documents\visual studio 2013\Projects\HDCAR\HDCAR\MainPage.xaml.cs    55  35  HDCAR

代码:

    SystemMediaTransportControls systemControls;
     void Alfa4c_Click(object sender, RoutedEventArgs e)
    {
        // get folder app is installed to
        var installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
        // get folders mp3 files are installed to.
        var resourcesFolder = await installFolder.GetFolderAsync("Audio");
        // open the mp3 file async
        var audioFile = await mp3FilesFolder.GetFileAsync("Alfa4c.mp3");
        var stream = await audioFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
        // play dat funky music
        MediaElement mediaplayer = new MediaElement();
        mediaplayer.SetSource(stream, audioFile.ContentType);
        mediaplayer.Play();
    }

【问题讨论】:

    标签: c# wpf windows-phone-8.1


    【解决方案1】:

    您需要将其设为async void 方法:

    async void Alfa4c_Click(object sender, RoutedEventArgs e)
    {
       // Your code...
    

    这允许您在方法中使用await

    请注意,您可能还希望正确处理您的流。这将需要一些额外的工作:

        using(var stream = await audioFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
        {
            // play dat funky music
            MediaElement mediaplayer = new MediaElement();
            mediaplayer.SetSource(stream, audioFile.ContentType);
    
            var tcs = new TaskCompletionSource<bool>();
            mediaplayer.CurrentStateChanged += (o,e) =>
            {
                if (mediaplayer.CurrentState != MediaElementState.Opening && 
                    mediaplayer.CurrentState != MediaElementState.Playing && 
                    mediaplayer.CurrentState != MediaElementState.Buffering &&
                    mediaplayer.CurrentState != MediaElementState.AcquiringLicense)
                    {
                        // Any other state should mean we're done playing
                        tcs.TrySetResult(true);
                    }
            };
            mediaplayer.Play();
            await tcs.Task; // Asynchronously wait for media to finish
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多