如何同时在多个设备中播放声音
本文关键字:播放声音 何同时 | 更新日期: 2023-09-27 17:56:25
我想同时在三个外部声卡中播放声音,我的意思是当我单击一个按钮时,我可以听到来自三个扬声器的声音,这些扬声器与我的三个声卡有关。我有一个函数,但它只在一个设备中播放声音,它找到的第一个,我的意思是在这个代码中第一个设备是数字 0,所以它在里面播放声音,但是如果你一开始写设备 1 号,它会在其中播放声音,作为结论它只在一个设备中播放声音,它不能同时适用于所有设备。这是它的代码:
public void playAllAvailableDevices()
{
//create a new class for each wav file & output etc.
WaveOut waveOut1 = new WaveOut();
WaveFileReader waveReader1 = new WaveFileReader(fileName);
WaveOut waveOut2 = new WaveOut();
WaveFileReader waveReader2 = new WaveFileReader(fileName);
WaveOut waveOut3 = new WaveOut();
WaveFileReader waveReader3 = new WaveFileReader(fileName);
switch (waveOutDevices)
{
case 1:
waveOut1.Init(waveReader1);
waveOut1.DeviceNumber = 0;
waveOut1.Play();
break;
case 2:
waveOut1.Init(waveReader1);
waveOut1.DeviceNumber = 0;
waveOut1.Play();
waveOut2.Init(waveReader2);
waveOut2.DeviceNumber = 1;
waveOut2.Play();
break;
case 3:
waveOut1.Init(waveReader1);
waveOut1.DeviceNumber = 0;
waveOut1.Play();
waveOut2.Init(waveReader2);
waveOut2.DeviceNumber = 1;
waveOut2.Play();
waveOut3.Init(waveReader3);
waveOut3.DeviceNumber = 2;
waveOut3.Play();
break;
}}
文件名是我要播放的声音文件的名称,在我的代码中,我从 darabase 获取此名称:
private void btnAlarm1_Click(object sender, EventArgs e)
{
OdbcConnection cn = new OdbcConnection("DSN=cp1");
cn.Open();
OdbcCommand cmd1 = new OdbcCommand("select chemin from alarme where code_alarme=41", cn);
cmd1.Connection = cn;
fileName = cmd1.ExecuteScalar().ToString();
wave = new WaveOut();
playAllAvailableDevices();
}
你能帮我找到解决方案吗????提前谢谢你。日安。
在调用 Init
之前,您需要在 WaveOut 对象上设置 DeviceNumber
属性。你可以使用一个简单的函数来清理你的代码:
private void PlaySoundInDevice(int deviceNumber, string fileName)
{
if (outputDevices.ContainsKey(deviceNumber))
{
outputDevices[deviceNumber].WaveOut.Dispose();
outputDevices[deviceNumber].WaveStream.Dispose();
}
var waveOut = new WaveOut();
waveOut.DeviceNumber = deviceNumber;
WaveStream waveReader = new WaveFileReader(fileName);
// hold onto the WaveOut and WaveStream so we can dispose them later
outputDevices[deviceNumber] = new PlaybackSession { WaveOut=waveOut, WaveStream=waveReader };
waveOut.Init(waveReader);
waveOut.Play();
}
private Dictionary<int, PlaybackSession> outputDevices = new Dictionary<int, PlaybackSession>();
class PlaybackSession
{
public IWavePlayer WaveOut { get; set; }
public WaveStream WaveStream { get; set; }
}
字典保留了WaveOut,因此在播放过程中不会收集垃圾,并允许我们正确清理。在退出应用程序之前,请确保正确清理:
private void DisposeAll()
{
foreach (var playbackSession in outputDevices.Values)
{
playbackSession.WaveOut.Dispose();
playbackSession.WaveStream.Dispose();
}
}
现在,您可以使用 for 循环在所有可用设备中播放,而不是要求您复制代码的 switch 语句:
public void PlayInAllAvailableDevices(string fileName)
{
int waveOutDevices = WaveOut.DeviceCount;
for (int n = 0; n < waveOutDevices; n++)
{
PlaySoundInDevice(n, fileName);
}
}
我认为您正在寻找的是BASS音频库:
http://www.un4seen.com/
这也可能有效:
http://www.alvas.net/alvas.audio.aspx
我不认为 C# 可以在没有上面列出的第三方加载项的情况下执行此操作。 也许比我聪明的人可以帮助你让它工作,但如果没有,这些库会帮助你走上你想要的道路。