user4433485
user4433485

Reputation:

Windows Phone 8.1 Music on click event

I am currently trying to play a mp3 file when click on button, I am trying to use the function like he did: How can I play mp3 files stored in my Windows Phone 8.1 solution? but it's not working well, it say

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

The code:

    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();
    }

Upvotes: 1

Views: 96

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564851

You need to make this an async void method:

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

This allows you to use await within the method.

Note you may also want to dispose of your stream correctly. That would require a bit of extra work:

    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
    }
}

Upvotes: 3

Related Questions