私は単純な .wav プレーヤーを書いています。再生ボタン、停止ボタンの 2 つのボタンがあります。
私は2つの解決策を持っています:
1. Play() API を使用して .wav ファイルを再生します。Stop() API を使用して停止します。
問題は、Play() API が別のスレッドでオーディオを再生するため、.wav ファイルが停止しているときに何かを実行できないことです (たとえば、[再生] ボタンを無効にする)。
2. 自分でスレッドを作成し、このスレッド内で PlaySync() API を使用し、オーディオが停止した後にタスクを実行します。次に、ユーザーが停止ボタンをクリックすると、Stop() 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();
}
});
}
}