我正在写一个简单的.wav播放器。有两个按钮:播放按钮,停止按钮。
我有2个解决方案:
问题是当.wav文件停止时我无法做某事(例如禁用播放按钮),因为Play()api在另一个线程中播放音频。
然而,我发现Stop()api并没有真正停止音频。
有谁知道为什么?
private SoundPlayer player;
//...
private async void PlayButton_Click(object sender, RoutedEventArgs e)
{
dynamic call = employeeDataGrid.SelectedItem;
if (call == null)
{
await this.ShowMessageDialogAsync("错误", "请选择通话");
return;
}
playButton.IsEnabled = false;
playButton.Visibility = Visibility.Collapsed;
stopButton.Visibility = Visibility.Visible;
player = new SoundPlayer(call.recording);
Utility.PlayTone(player, new Action(() =>
{
Dispatcher.Invoke(() =>
{
stopButton.IsEnabled = false;
stopButton.Visibility = Visibility.Collapsed;
playButton.IsEnabled = true;
playButton.Visibility = Visibility.Visible;
});
}));
}
private void StopButton_Click(object sender, RoutedEventArgs e)
{
if (player != null)
player.Stop();
}
public static class Utility
{
public static void PlayTone(SoundPlayer player, Action callback)
{
Task.Factory.StartNew(() =>
{
player.PlaySync();
if (callback != null)
{
callback();
}
});
}
}