views:

597

answers:

3

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 wont start. What could possibly be wrong with this code?

+1  A: 

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.

AnthonyWJones
Thanks for your Reply!The MediaFailed event, does not get fired.And I checked the CurrentState property and when i trying to change track it just says "Closed".Closed? What does that mean? The source is correkt.
@krika02: Means that the MediaElement believes that it currently contains no media. Which is a bit strange since you've clearly set it. If you initially specific track2 does it actually manage to play it?
AnthonyWJones
+1  A: 

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.

Jason Roberts
Works! Thank you very much!
I have no idea why and how, but this seems to work. Thanks!
DrJokepu
A: 

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.