【问题标题】:Play sound in both speaker and headset wpf在扬声器和耳机 wpf 中播放声音
【发布时间】:2014-04-06 01:35:00
【问题描述】:

我有一个 wpf 应用程序,我正在使用 soundPlayer 类播放声音(例如铃声)。目前,声音在扬声器或耳机上播放(如果已插入)。 即使插入耳机,我也希望应用程序在扬声器上播放音调。我知道在 android 中有方法可以做到这一点,但在 wpf 中找不到任何方法。任何帮助表示赞赏。谢谢!

分享示例代码:

  public void detectDevices()
    {
        int waveOutDevices = WaveOut.DeviceCount;
        switch (waveOutDevices)
        {
            case 1:
                var wave1 = new WaveOut();
                wave1.DeviceNumber = 0;
                playSound(0); 

                break;
            case 2:
                var wave2 = new WaveOut();
                wave2.DeviceNumber = 0;
                playSound(0);

                var wave3 = new WaveOut();
                wave3.DeviceNumber = 1;
                playSound(1); 

                break;

        }
    }

    public void playSound(int deviceNumber)
    {
        disposeWave();// stop previous sounds before starting
        waveReader = new NAudio.Wave.WaveFileReader(fileName);
        var waveOut = new NAudio.Wave.WaveOut();
        waveOut.DeviceNumber = deviceNumber;
        output = waveOut;
        output.Init(waveReader);
        output.Play();
    }

    public void disposeWave()
    {
        if (output != null)
        {
            if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
            {
                output.Stop();
                output.Dispose();
                output = null;
            }
        }
        if (wave != null)
        {
            wave.Dispose();
            wave = null;
        }
    }

case eSelector.startIncomingRinging:

                fileName = ("Ring.wav");
                detectDevices();

【问题讨论】:

    标签: c# wpf speaker soundplayer headphones


    【解决方案1】:

    我的回答假设您使用计算机的多个输出设备,而不仅仅是扬声器上可用的耳机插孔。

    SoundPlayer 始终使用默认输出设备播放,无法更改。一种替代方法是使用诸如 NAudio 之类的库,它提供了更多选项。

    This article 提供了如何使用 NAudio 更改音频输出设备的代码示例。

    您的问题可以通过使用多个WaveOut 实例来解决。

    var waveOut1 = new WaveOut();
    waveOut1.DeviceNumber = 0; // First device
    
    var waveOut2 = new WaveOut();
    waveOut2.DeviceNumber = 1; // Second device
    

    可以从WaveOut.DeviceCount检索设备总数。

    【讨论】:

    • 感谢 Lukazoid 对 Naudio 的建议,但我认为我离让它发挥作用还有一步之遥。请查看已编辑的问题。欢迎提出建议。
    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多