由于 Microsoft Surface 应用程序中缺少声音效果,我尝试在字典中使用声音文件 (.wav) 构建“声音库”。
声音文件很短。
路径 = PathToFile
我的“声音库”:
Dictionary<string, MediaElement> soundBank = new Dictionary<string, MediaElement>(29);
soundBank = new Dictionary<string, MediaElement>(20);
soundBank.Add("1", new MediaElement());
soundBank.Add("2", new MediaElement());
soundBank.Add("3", new MediaElement());
soundBank.Add("4", new MediaElement());
soundBank.Add("A", new MediaElement());
soundBank.Add("BE", new MediaElement());
soundBank.Add("CF", new MediaElement());
...
foreach (var item in soundBank)
{
Console.WriteLine(item.Key);
//soundBank[item.Key] = new MediaElement();
soundBank[item.Key].Source = new Uri(path);
soundBank[item.Key].LoadedBehavior = MediaState.Manual;
soundBank[item.Key].UnloadedBehavior = MediaState.Manual;
soundBank[item.Key].Volume = 1;
soundBank[item.Key].MediaEnded += new System.Windows.RoutedEventHandler(mp_MediaEnded);
如果我尝试播放多个声音(on_button_click),声音会延迟或根本不播放:
public void play(string key)
{
soundBank[key].Stop();
soundBank[key].Play();
}
void mp_MediaEnded(object sender, System.Windows.RoutedEventArgs e)
{
((MediaElement)e.Source).Stop();
}
SoundPlayer 和 MediaPlayer 不适合,因为它们会停止所有其他播放的声音。