简体   繁体   English

使用C#WPF播放资源文件中的声音

[英]Play sound from resource file using c# wpf

I was wondering if it's possible to play sound file (wav, mp3) from a Resource File. 我想知道是否可以从资源文件播放声音文件(wav,mp3)。 I need to play two sounds - one for background music (async in a loop), second one for a random sound. 我需要播放两种声音-一种用于背景音乐(循环异步),另一种用于随机声音。 I tried SoundPlayer , but BGM stops when I play a random sound (of course I use two separate SoundPlayers). 我尝试了SoundPlayer ,但是当我播放随机声音时BGM会停止(当然我使用两个单独的SoundPlayers)。 So, I'm looking for a C# WPF Library which I can use to play two or more sounds in one time from Resources. 因此,我正在寻找一个C#WPF库,该库可用于从参考资料中一次播放两个或多个声音。 I'd be grateful if somebody could provide an example. 如果有人可以提供一个例子,我将不胜感激。 Thank You in advance. 先感谢您。

Have you tried using NAudio library? 您是否尝试过使用NAudio库? It is very easy and supports lots of functionalities. 它非常简单,并支持许多功能。

I solved my problem with this code: 我用以下代码解决了我的问题:

    private NAudio.Wave.WaveFileReader wave = new NAudio.Wave.WaveFileReader(Properties.Resources.bgm);
    private NAudio.Wave.DirectSoundOut outs = null;
    public void PlayBGM()
    {
        if (outs == null)
        {
            outs = new NAudio.Wave.DirectSoundOut();
            outs.Init(new NAudio.Wave.WaveChannel32(wave));
        }
        outs.Play();
    }

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

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