Marius
Marius

Reputation: 9674

How can I specify MediaElement.Source with non-relative uri?

We have some WPF modules which are hosted in a cpp unmanaged/managed application. This enviroment is causing troubles when specifying relative Uri's for media content. For example, I have no problem of doing something like this in a testapp:

    <MediaElement Grid.Row="0"  x:Name="player"  Source="media\Getting started with.wmv" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="Fill" 
        MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded"/>

But, as mentioned, this does not work in production code.

If I try to use the pack schema like this:

Source="pack://application:,,,/media/Getting started with.wmv"

I get the exception:

Cannot navigate to application resource 'pack://application:,,,/media/Getting started with.wmw' by using a WebBrowser control. For URI navigation, the resource must be at the application�s site of origin. Use the pack://siteoforigin:,,,/ prefix to avoid hard-coding the URI.

If I try to use the 'siteoforigin' schema like this:

Source="pack://siteoforigin:,,,/media/Getting started with Olga 7.wmv"

I get another error:

Application identity is not set.

The media file is set up as "Content" and with "copy always".

How can I specify the MediaElement source using an absolute uri in a Wpf desktop application?

Upvotes: 2

Views: 7882

Answers (2)

user3808155
user3808155

Reputation: 1

Only you need to do this:

        MediaElement bb = new MediaElement();
        stage.Children.Add(bb);
        bb.Source = new Uri("Recursos/MagicWandNoise.wav", UriKind.Relative);
        Debug.WriteLine("URL:" + bb.Source);
        bb.LoadedBehavior = MediaState.Manual;
        bb.Play();

And then add the Binary Resources in your folder debug, check this link

Remember the media element to work fine, you need to add in a Visual Three

        Canvas.Children.Add(bb);

Upvotes: -1

Marius
Marius

Reputation: 9674

I found a solution (kinda). I am guessing that the relative url's can not be resolved because the main .exe is an cpp mfc application. So in order to create absolute uri's I did something like this:

        player.Source = new Uri(CreateAbsolutePathTo("media/Getting started with.wmv"), UriKind.Absolute);

    private static string CreateAbsolutePathTo(string mediaFile)
    {
        return Path.Combine(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName, mediaFile);
    }

I am binding to a viewmodel so this logic is wrapped into a property on the viewmodel and the source is databound in xaml.

Its working, but its not as pretty as I would like it to be.

Upvotes: 3

Related Questions