如何在c#中暂停和恢复音频

时间:2015-08-11 14:27:33

标签: c# .net wpf audio

我正在研究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;
}

2 个答案:

答案 0 :(得分:1)

使用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); 
}

答案 1 :(得分:0)

Soundplayer不支持暂停和恢复。您可以改用WPF MediaElement。

如果你必须使用Soundplayer,你可以每秒用一首柔和的歌曲开始一个新的主题。之后,你必须在暂停方法中静音。在恢复方法中,您必须检查哪个线程处于最佳时间。

但我认为这将是最可怕的解决方案。

干杯