Question

I'm making part of a musical typing game, and while I've created some code that will play songs that are already loaded into the XNA Content Manager, I'm trying to create something that can play MP3 and WAV based on XML files. This is what I have for "hard-coded" songs:

    Song music;
    SoundEffect effect;

    Dictionary<string, SoundEffect> effectlist = new Dictionary<string, SoundEffect>();
    Dictionary<string, Song> songlist = new Dictionary<string, Song>();

    public Audio()
    { 
    }

    public void playSong(string songName)
    {
        songlist.TryGetValue(songName, out music);
        MediaPlayer.Play(music);
    }
    public void playEffect(string eftName)
    {
        effectlist.TryGetValue(eftName, out effect);
        effect.Play();
    }


    public void addSong(string aKey, Song aSong)
    {
        songlist.Add(aKey, aSong);
    }
    public void addEffect(string iKey, SoundEffect anEffect)
    {
        effectlist.Add(iKey, anEffect);
    }

I only know the basics of XML, like displaying text from an XML file in a console application. How can I use XML to play sounds?

Was it helpful?

Solution

You can't use XML to play sounds, you can use XML to data drive your application so that you can play sounds based on the content of the xml file.

For example, say you had something like

<songs>
    <song name="songA" file="1.mp3" />
    <song name="songB" file="2.mp3" />
    <song name="songC" file="3.mp3" />
</songs>

You can read the xml into something like an xDocument, and when your application requests that you play "songA", you can lookup that song in your xDocument and play the associated music file.

This lets you change the behaviour of your application through configuration rather than having everything hard-coded.

Edit: Rough code example so you get the idea...

   private XDocument m_Songs;
     public Audio()
    { 
         m_Songs = XDocument.Load("My XML Source");
    }


    public void playSong(string songName)
    {
        XElement match = m_Songs.Descendants()
            .Where(x => x.Name.LocalName == "song")
            .FirstOrDefault(x => x.Attribute("name").Value == "songName");

        if (match == null)
            return;

        songlist.TryGetValue(match.Attribute("file").Value, out music);
        MediaPlayer.Play(music);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top