using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using System.IO; namespace TalkingIsAFreeAction { public static class Audio { public static Dictionary sounds; public static Dictionary music; public static SoundEffectInstance currentMusic = null; public static void LoadContent(Game game) { LoadMusic(game); LoadSound(game); } public static void LoadMusic(Game game) { music = new Dictionary(); DirectoryInfo di = new DirectoryInfo(game.Content.RootDirectory + "/Music"); FileInfo[] fi = di.GetFiles("*", SearchOption.AllDirectories); List loadableAssets = new List(); foreach (FileInfo f in fi) { string fullname = f.FullName; string cutname = fullname.Substring(f.FullName.LastIndexOf("\\Content\\") + 9); loadableAssets.Add(cutname.Replace("\\", "/")); //Replace \ with / } for (int i = 0; i < loadableAssets.Count; i++) { string name = loadableAssets[i].Substring(0, loadableAssets[i].LastIndexOf(".")); if (name.Contains("/")) name = name.Substring(name.LastIndexOf("/") + 1); if (loadableAssets[i].EndsWith(".xnb")) //Sound. Probably { SoundEffect sound = game.Content.Load(loadableAssets[i].Substring(0, loadableAssets[i].LastIndexOf("."))); sound.Name = name; music.Add(name, sound); } } } public static void LoadSound(Game game) { sounds = new Dictionary(); DirectoryInfo di = new DirectoryInfo(game.Content.RootDirectory + "\\Sound"); FileInfo[] fi = di.GetFiles("*", SearchOption.AllDirectories); List loadableAssets = new List(); foreach (FileInfo f in fi) { string fullname = f.FullName; string cutname = fullname.Substring(f.FullName.LastIndexOf("\\Content\\") + 9); loadableAssets.Add(cutname.Replace("\\", "/")); //Replace \ with / } for (int i = 0; i < loadableAssets.Count; i++) { string name = loadableAssets[i].Substring(0, loadableAssets[i].LastIndexOf(".")); if (name.Contains("/")) name = name.Substring(name.LastIndexOf("/") + 1); if (loadableAssets[i].EndsWith(".xnb")) //Sound. Probably { SoundEffect sound = game.Content.Load(loadableAssets[i].Substring(0, loadableAssets[i].LastIndexOf("."))); sound.Name = name; sounds.Add(name, sound); } } } public static void PlayMusic(string name, bool loop = true) { if (currentMusic != null) { if (currentMusic.State == SoundState.Playing) { currentMusic.Stop(); } } currentMusic = music[name].CreateInstance(); currentMusic.IsLooped = loop; currentMusic.Play(); } public static void PlaySound(string name) { if (sounds.ContainsKey(name)) { sounds[name].CreateInstance().Play(); } } public static SoundEffectInstance PrepareSound(string name) { if (sounds.ContainsKey(name)) { return sounds[name].CreateInstance(); } return null; } } }