简体   繁体   中英

Play sound in both speaker and headset wpf

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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