简体   繁体   中英

Playing Audio file freezing UI using C#

In this particular application I am showing Video using Web Cam.
When I press any button it runs Audio file using SoundPlayer .

Code to Run Audio

System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"Audio\audio1.wav");
player.PlayLooping();

This code snippet freezing the UI even if I put this code in thread still my UI is freezing

So can anyone please tell me how I can solve this problem. Thank you

Edit1:

So in above code snippet I am declaring Sound Player object Globally

System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"Audio\audio1.wav");

and calling function PlayAudio() on Button click Event

private void PlayAudio()
{
    player.PlayLooping();
}

It should NOT freeze the UI, unless there is some other blocking code running. Below is a sample 'Hello World' WPF code with your code sample -

XAML -

<StackPanel>
    <Button Content="Play" Height="50" Width="100" Click="Button_Click"/>
    <Button Content="Test" Height="50" Width="100" Click="Button_Click_1"/>
    <TextBlock x:Name="txtSample" Text="Hello"/>
</StackPanel>

xaml.cs -

public MainWindow()
{
    InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"Audio\audio1.wav");
    player.PlayLooping();
}

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    txtSample.Text = Guid.NewGuid().ToString();
}

Now click on the Play button to play the sound, now while the sound is playing click on Test button any number of times it should not freeze.

Also as per Microsoft documentation PlayLooping should not hang UI as it runs in a new thread by default.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM