Search code examples
c#soundplayer

Playing music from collection with SoundPlayer


So I am doing a simple piano and trying to traverse the collection where I stored the notes, but the SoundPlayer doesn't want to play them properly in "without debugging mode", playing only the last one. However when I put a breakpoint there it plays all of them

public static List<MusicNote> music = new List<MusicNote>(15);
public static void PlayAll()
    {
        SoundPlayer sp = new SoundPlayer();
        for (int i = 0; i <= music.Count - 1; i++)
        {
            string text = music[i].pitch.ToString();
            sp.SoundLocation = (@"c:\my path here\" + text + ".wav");
            sp.Play();
            sp.Stop();
        }
    }

Pitch is simply ordinal number to link to file.
Thanks in advance


Solution

  • U better use PlaySyn in order to tell your program to wait until the music complete

        // Create new SoundPlayer in the using statement.
        using (SoundPlayer player = new SoundPlayer())
        {
          for (int i = 0; i <= music.Count - 1; i++)
               {
                   string text = music[i].pitch.ToString();
                   sp.SoundLocation = (@"c:\my path here\" + text + ".wav");
                   // Use PlaySync to load and then play the sound.
                   // ... The program will pause until the sound is complete.
                   player.PlaySync();
               }
        }