Play sound in both speaker and headset wpf

大兔子大兔子 提交于 2019-12-25 02:46:25

问题


I have an wpf application and i am using the soundPlayer class to play sound (for eg ringtone). Currently the tone plays either on speakers or on the headset (if its plugged in). I would like the application to play the tone on speaker even when the headsets are plugged in. I know there are ways to do this in android, but couldn't find any in wpf. Any help is appreciated. Thanks !

Sharing sample code :

  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();

回答1:


My answer assumes you are using multiple output devices from your computer and not just the headphone jack available on your speakers.

SoundPlayer always plays using the default output device with no way to change it. One alternative would be to use a library such as NAudio which offers more options.

This article offers code examples of how to change the audio output device using NAudio.

Your question could be satisfied by making use of multiple WaveOut instances.

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

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

The total number of devices can be retrieved from WaveOut.DeviceCount.



来源:https://stackoverflow.com/questions/22173273/play-sound-in-both-speaker-and-headset-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!