I'm writing a simple .wav player. There are two buttons: Play button, Stop button.
I've 2 solutions:
1. use Play() api to play a .wav file; use Stop() api to stop it.
The issue is I cannot do something when a .wav file is stopped (eg. disable the Play button), since Play() api play the audio in another thread.
2. create a thread myself, and use PlaySync() api inside this thread, and do the task after the audio is stopped. Then when user click the stop button, call Stop() api to stop it.
However, I found that the Stop() api does not really stop the audio.
Does anyone know why?
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();
}
});
}
}