0

Using the WP8 emulator, I have Media Element (inside the Layout Root of my XAML file, so the element is part of the visual tree at runtime), and I'm trying to programmatically trigger it to play from the code behind.

I'm using the Caliburn Micro EventAggregator to send a message when something in my app's backend requires a sound to be played. In the view's code behind I'm using IHandle to set the media element's Source and trigger Play.

public void Handle(ToneMessage message)
{
    MediaElem.Source = message.ToneUri;

    MediaElem.Play();
}

When I trigger the message event, no sound is played. However, if I put a breakpoint on MediaElem.Play(), when I step over it, the sound plays.

I don't know what's happening, basically my code works only when I'm stepping over it with the debugger. I'm still on the UI thread (even tried explicitly using the Dispatcher).

Any ideas are welcomed.

drl
  • 811
  • 2
  • 11
  • 21
  • 1
    Maybe this can help: http://stackoverflow.com/questions/10984038/unable-to-play-sound-in-windows-8 – the_lotus Nov 04 '13 at 15:29
  • Thanks for the comment, in the link there were mentions of using MediaOpened, it seems it was the correct choice. – drl Nov 04 '13 at 17:24

1 Answers1

1

If it works with the debugger and not in the actual application, you can be almost certain it's a timing issue.

In your case, the problem is that you're not waiting for the sound to load before trying to play it. It works on the emulator because the execution is paused, giving enough time to load the sound.

Before setting the source, subscribe to the MediaOpened event of the MediaElement. Then, in that event, call the Play method to play the sound.

Alternatively, you can set the AutoPlay property to true to automatically play the sound once it has finished downloading.

Kevin Gosse
  • 38,392
  • 3
  • 78
  • 94
  • You were spot on, I was trying to play the media file before it was loaded. I thought somehow it wouldn't play unless it's already loaded. – drl Nov 04 '13 at 17:24