简体   繁体   English

使用 C# 播放音频文件冻结 UI

[英]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 .当我按下任何按钮时,它会使用SoundPlayer运行Audio file

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即使我将此代码放在线程中,此代码片段也会冻结 UI,但我的 UI 仍处于冻结状态

So can anyone please tell me how I can solve this problem.所以任何人都可以告诉我如何解决这个问题。 Thank you谢谢

Edit1:编辑1:

So in above code snippet I am declaring Sound Player object Globally所以在上面的代码片段中,我在全局声明了 Sound Player 对象

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

and calling function PlayAudio() on Button click Event并在按钮单击事件上调用函数PlayAudio()

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

It should NOT freeze the UI, unless there is some other blocking code running.它不应该冻结 UI,除非有其他一些阻塞代码正在运行。 Below is a sample 'Hello World' WPF code with your code sample -以下是带有您的代码示例的示例“Hello World”WPF 代码 -

XAML - 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 - 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.现在单击“ Play按钮播放声音,现在在播放声音时单击“ Test按钮不应该冻结任何次数。

Also as per Microsoft documentation PlayLooping should not hang UI as it runs in a new thread by default.同样根据Microsoft 文档,默认情况下PlayLooping不应挂起 UI,因为它在新线程中运行。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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