我目前正尝试在单击按钮时播放 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();
}
最佳答案
您需要将其设为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
}
}
关于c# - Windows Phone 8.1 音乐点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32595253/