在扬声器和耳机 wpf 中播放声音



我有一个 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();

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

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

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

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

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

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

最新更新