Change Source in MediaElement (SILVERLIGHT)

自古美人都是妖i 提交于 2019-12-23 19:41:26

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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).



来源:https://stackoverflow.com/questions/2248983/change-source-in-mediaelement-silverlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!