我正在尝试制作乐器类型的应用程序。我遇到的问题是只有在旧声音完成后才会播放新声音。我希望能够同时播放它们。
这就是我的代码的样子:
首先,MyWave 类只保存一个音频缓冲区和一些其他信息:
class MyWave
{
public AudioBuffer Buffer { get; set; }
public uint[] DecodedPacketsInfo { get; set; }
public WaveFormat WaveFormat { get; set; }
}
在 SoundPlayer 类中:
private XAudio2 xaudio;
private MasteringVoice mvoice;
Dictionary<string, MyWave> sounds;
// Constructor
public SoundPlayer()
{
xaudio = new XAudio2();
xaudio.StartEngine();
mvoice = new MasteringVoice(xaudio);
sounds = new Dictionary<string, MyWave>();
}
// Reads a sound and puts it in the dictionary
public void AddWave(string key, string filepath)
{
MyWave wave = new MyWave();
var nativeFileStream = new NativeFileStream(filepath, NativeFileMode.Open, NativeFileAccess.Read, NativeFileShare.Read);
var soundStream = new SoundStream(nativeFileStream);
var buffer = new AudioBuffer() { Stream = soundStream, AudioBytes = (int)soundStream.Length, Flags = BufferFlags.EndOfStream };
wave.Buffer = buffer;
wave.DecodedPacketsInfo = soundStream.DecodedPacketsInfo;
wave.WaveFormat = soundStream.Format;
this.sounds.Add(key, wave);
}
// Plays the sound
public void Play(string key)
{
if (!this.sounds.ContainsKey(key)) return;
MyWave w = this.sounds[key];
var sourceVoice = new SourceVoice(this.xaudio, w.WaveFormat);
sourceVoice.SubmitSourceBuffer(w.Buffer, w.DecodedPacketsInfo);
sourceVoice.Start();
}
}
谷歌不是很有帮助,我找不到任何有用的东西。那么如何同时播放多个声音呢?