我正在wpf应用程序上。我想暂停并恢复音频,但歌曲从头开始播放。
//c# code
System.Media.SoundPlayer sp = new System.Media.SoundPlayer(@"D:\Intro.wav");
private void play_Click(object sender, EventArgs e)
{
sp.Play();
play_btn.Enabled = false;
stop_btn.Enabled = true;
}
private void stop_Click(object sender, EventArgs e)
{
sp.Stop();
stop_btn.Enabled = false;
play_btn.Enabled = true;
}
最佳答案
使用System.Windows.Controls.MediaElement
而不是System.Media.SoundPlayer
。它具有Pause
函数。
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="320*"/>
<RowDefinition Height="50*"/>
</Grid.RowDefinitions>
<MediaElement x:Name="MediaPlayer" Grid.RowSpan="1" LoadedBehavior="Manual"/>
<StackPanel Orientation="Horizontal" Grid.Row="1" HorizontalAlignment="Center">
<Button x:Name="btnPlay" Content="Play" Click="btnPlay_Click" Width="50" Height="25" Margin="5"/>
<Button x:Name="btnStop" Content="Stop" Click="btnStop_Click" Width="50" Height="25" Margin="5"/>
<Button x:Name="btnMoveBack" Content="Back" Click="btnMoveBack_Click" Width="50" Height="25" Margin="5"/>
<Button x:Name="btnMoveForward" Content="Forward" Click="btnMoveForward_Click" Width="50" Height="25" Margin="5"/>
</StackPanel>
</Grid>
private void IsPlaying(bool flag)
{
btnPlay.IsEnabled = flag;
btnStop.IsEnabled = flag;
btnMoveBack.IsEnabled = flag;
btnMoveForward.IsEnabled = flag;
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
IsPlaying(true);
if (btnPlay.Content.ToString() == "Play")
{
MediaPlayer.Play();
btnPlay.Content = "Pause";
}
else
{
MediaPlayer.Pause();
btnPlay.Content = "Play";
}
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
MediaPlayer.Pause();
btnPlay.Content = "Play";
IsPlaying(false);
btnPlay.IsEnabled = true;
}
private void btnMoveBack_Click(object sender, RoutedEventArgs e)
{
MediaPlayer.Position -= TimeSpan.FromSeconds(10);
}
private void btnMoveForward_Click(object sender, RoutedEventArgs e)
{
MediaPlayer.Position += TimeSpan.FromSeconds(10);
}
关于c# - 如何在C#中暂停和恢复音频,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31944522/