Iterate through the enumeration and check the state of the MediaPlayer before advancing to the next song

StackOverflow https://stackoverflow.com/questions/7007185

Question

I need to play songs in my IEnumerable collection, but there is so many problem with this method. If I use timer to check the MediaState, it may works, however when I navigate from this page, the class will be cancel and the music will be stopped. The reason I want to do this is to be able to play song from different albums:

My code:

    private SongCollection mySongCollection;
    IEnumerable<Song> ultimateCollection;

    mySongCollection = library.Albums[index].Songs;
    ultimateCollection = mySongCollection.Concat(library.Albums[1].Songs);

    foreach (Song a in ultimateCollection)
      {
      while (MediaPlayer.State == MediaState.Playing || MediaPlayer.State == MediaState.Paused)
                    {
                       //while MediaState still playing, dont play next song
                    }
                        MediaPlayer.Play(a);
       }
Was it helpful?

Solution

If I understand correctly, you want the collection ultimateCollection to remain after you have moved away from the page. In your example it makes sense that it is destroyed since it is a field variable of the page. What you want to do is to have a static playlist that is accessible from everywhere in your app.

I would suggest moving ultimateCollection to App.xaml

public IList<Song> UltimateCollection {get; private set;}

// and then somewhere else in App.xaml.cs where your player is looping through the songs
    int i=0;
    while(i<UltimateCollection.Count)
    {
        Song a = UltimateCollection[i];
        MediaPlayer.Play(a);
        while (MediaPlayer.State == MediaState.Playing || MediaPlayer.State == MediaState.Paused)
        {
            //while MediaState still playing, dont play next song
        }
    }

then from the elsewhere in your app, say another page, you could add to that collection by

App.UltimateCollection.Add(someSong);

There may be some threading issues when adding to the collection, but this should allow you add songs to a playlist and navigate away from a page. Let me know if this helps.

Cheers, Al.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top