C# Windows Phone 8.1单击音乐事件
我目前正试图在点击按钮时播放mp3文件,我正试图像他那样使用该功能: 但它说,效果不好C# Windows Phone 8.1单击音乐事件,c#,wpf,windows-phone-8.1,C#,Wpf,Windows Phone 8.1,我目前正试图在点击按钮时播放mp3文件,我正试图像他那样使用该功能: 但它说,效果不好 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 stu
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...
这允许您在方法中使用wait
注意:您可能还希望正确处理流。这需要一些额外的工作:
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
}
}
使用(var stream=await audioFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
//播放时髦的音乐
MediaElement mediaplayer=新的MediaElement();
mediaplayer.SetSource(流,audioFile.ContentType);
var tcs=new TaskCompletionSource();
mediaplayer.CurrentStateChanged+=(o,e)=>
{
if(mediaplayer.CurrentState!=MediaElementState.Opening&&
mediaplayer.CurrentState!=MediaElementState.Playing&&
mediaplayer.CurrentState!=MediaElementState.Buffering&&
mediaplayer.CurrentState!=MediaElementState.AcquiringLicense)
{
//任何其他州都应该意味着我们玩完了
tcs.TrySetResult(真);
}
};
mediaplayer.Play();
wait tcs.Task;//异步等待媒体完成
}
}