在扬声器和耳机WPF中播放声音 [英] Play sound in both speaker and headset wpf
问题描述
我有一个wpf应用程序,并且我正在使用soundPlayer类播放声音(例如,铃声).当前,该声音在扬声器或耳机(如果已插入)上播放. 我希望该应用程序即使在插入头戴式耳机时也能在扬声器上播放音调.我知道可以在android中进行此操作,但在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 !
共享示例代码:
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
始终使用默认的输出设备播放,而无法对其进行更改.一种替代方法是使用诸如 NAudio
之类的库,该库提供更多选项.
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.
本文提供了有关如何使用NAudio更改音频输出设备的代码示例.
This article offers code examples of how to change the audio output device using NAudio.
可以通过使用多个WaveOut
实例来满足您的问题.
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
可以从WaveOut.DeviceCount
检索设备总数.
这篇关于在扬声器和耳机WPF中播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!