Question

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.

Was it helpful?

Solution

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.

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