Question

I would like to change song on my MediaElent from track1.mp3 to track2.mp3. And here is the code:

MyMediaElement.Stop();
Uri u = new Uri("track2.mp3", UriKind.Relative);
MyMediaElement.Source=u;
MyMediaElement.Play();

The MediaElement change the source but just won't start. What could possibly be wrong with this code?

Was it helpful?

Solution

Try setting MyMediaElement.AutoPlay to true, as soon as the source changes it should play. You could also investigate using the MediaElement.SetSource() method which takes a stream rather than a uri.

OTHER TIPS

I had the same problem. I could set autoplay and the source in the XAML and it would work, but if I changed source in the code it would just do nothing.
I captured the MediaOpened event of the control.
The problem is that it hits Play() right after you changed the source, so the current state is closed. It takes a few clock cycles to change the state. So, if you put Play(); inside that event handler it will work.

You don't appear to be doing anything wrong. Here are a couple of diagnostics I would try:-

Specify track2 as the initial file does that work?

Attach to the MediaFailed event, does that get fired?

Bind a TextBlock to the CurrentState property to observe how the CurrentState has changed.

You set AutoPlay to false and then in the MediaOpened handler you do Play(). People kind of hinted towards the solution here but not very exact. You could also handle the MediaFailed event just in case the media fails to open for some reason (can't find file etc).

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