【发布时间】:2015-03-17 13:46:29
【问题描述】:
我想在我的程序中同时播放多个声音。看到在我之前很多人都问过这个问题,我浏览了他们,并决定尝试在不同的线程上播放声音。但是,我仍然遇到相同的问题,即当前播放的声音会出现新的声音。
我是否犯了错误,或者我是否误解了多线程这将是可能的? 实现这一目标的正确方法是什么?
public class SoundManager
{
private const int NUM_EFFECT_CHANNELS = 8;
private const int NUM_AMBIENT_CHANNELS = 2;
private static Thread[] ambientSounds = new Thread[NUM_AMBIENT_CHANNELS];
private static Thread[] soundEffects = new Thread[NUM_EFFECT_CHANNELS];
private static bool[] isPlaying = new bool[NUM_EFFECT_CHANNELS];
private static bool[] isAmbientPlaying = new bool[NUM_AMBIENT_CHANNELS];
#region public
public static void PlayAmbientSound(string soundFileName)
{
for (int channel = 0; channel < NUM_AMBIENT_CHANNELS; channel++)
{
if (isAmbientPlaying[channel])
continue;
ambientSounds[channel] = new Thread(() => { ambientPlayer(soundFileName, false, channel); });
isAmbientPlaying[channel] = true;
ambientSounds[channel].Start();
return;
}
}
public static void PlayAmbientSound(string soundFileName, bool loop)
{
for (int channel = 0; channel < NUM_AMBIENT_CHANNELS; channel++)
{
if (isAmbientPlaying[channel])
continue;
ambientSounds[channel] = new Thread(() => { ambientPlayer(soundFileName, loop, channel); });
isAmbientPlaying[channel] = true;
ambientSounds[channel].Start();
return;
}
}
public static void PlaySoundEffect(string soundFileName)
{
for (int channel = 0; channel < NUM_EFFECT_CHANNELS; channel++)
{
if (isPlaying[channel])
continue;
soundEffects[channel] = new Thread(() => { effectPlayer(soundFileName, false, channel); });
isPlaying[channel] = true;
soundEffects[channel].Start();
return;
}
}
public static void PlaySoundEffect(string soundFileName, bool loop)
{
for (int channel = 0; channel < NUM_EFFECT_CHANNELS; channel++)
{
if (isPlaying[channel])
continue;
soundEffects[channel] = new Thread(() => { effectPlayer(soundFileName, loop, channel); });
isPlaying[channel] = true;
soundEffects[channel].Start();
return;
}
}
public static void StopAmbient(int channel)
{
ambientSounds[channel].Abort();
isAmbientPlaying[channel] = false;
}
public static void StopEffect(int channel)
{
soundEffects[channel].Abort();
isPlaying[channel] = false;
}
#endregion
#region private
private static void effectPlayer(string soundFileName, bool loop, int channel)
{
Console.WriteLine("Started Effect on channel: " + channel + "...");
if (loop)
new SoundPlayer(soundFileName).PlayLooping();
else
new SoundPlayer(soundFileName).Play();
isPlaying[channel] = false;
Console.WriteLine("Channel " + channel + " finnished");
}
private static void ambientPlayer(string soundFileName, bool loop, int channel)
{
Console.WriteLine("Started Ambient on channel: " + channel + "...");
if (loop)
new SoundPlayer(soundFileName).PlayLooping();
else
new SoundPlayer(soundFileName).Play();
isAmbientPlaying[channel] = false;
Console.WriteLine("Channel " + channel + " finnished");
}
#endregion
}
【问题讨论】:
标签: c# multithreading audio