Search code examples
c#axwindowsmediaplayer

How to play all songs from List<Song> with Windows Media Player?


so I have a list class called SąrašasList and it has string item called vardas, which contains a path name to a song, I have few songs in this list, and also GUI with AX Windows Media player, but when I write :

private void axWindowsMediaPlayer1_Enter(object sender, EventArgs e)
{
    foreach (SąrašasList d in atrinktas)
    {
        axWindowsMediaPlayer1.URL = d.getVardas();
    }
}

It only plays the last song, but does not go to another, what should I do? I want this player to play all songs, one after the other.


Solution

  • Basically, what you're doing is iterating through all of your songs, and loading each one into the player. Of course, your player can only handle one of them, so the last one of your collection is effectively playing.

    What you should do is loading your first song, and at the end of each media, you have to load the n + 1 song.

    private System.Timers.Timer Timer; // Used to introduce a delay after the MediaEnded event is raised, otherwise player won't chain up the songs
    
    private void ScheduleSongs() {
        var count = 0;
        var firstSong = atrinktas.FirstOrDefault(); // using Linq
        if(firstSong == null) return;
        axWindowsMediaPlayer1.URL = firstSong.getVardas();
        // PlayStateChange event let you listen your player's state. 
        // https://msdn.microsoft.com/fr-fr/library/windows/desktop/dd562460(v=vs.85).aspx
        axWindowsMediaPlayer1.PlayStateChange += delegate(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e) { 
           if(e.newState == 8 && count < atrinktas.Count()) {
              count++;
              var nextSong = atrinktas[count];
              axWindowsMediaPlayer1.URL = nextSong.getVardas();
              Timer = new System.Timers.Timer() { Interval = 100 };
              Timer.Elapsed += TimerElapsed; // Execute TimerElapsed once 100ms is elapsed          
           } 
        };
    }
    
    private void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        Timer.Stop();
        Timer.Elapsed -= TimerElapsed;
        Timer = null;
    
        axWindowsMediaPlayer1.Ctlcontrols.play(); // Play the next song
    }