locked
Change Source of MediaElement and Image in Runtime Using VB Code RRS feed

  • Question

  • Hi,

    I am trying to develop a simple Windows 8.1 Store App using Visual Studio 2013 professional and Visual Basic as a programming language. I stumble at the following problem (the scenario is just for demonstration):

    For argument sake, say I have one MediaElement and one Image named myMediaElement and myImage. In the assets I have two audio and two picture files – Sound1.mp3, Sound2.mp3, Picture1.jpg and Picture2.jpg. And I have two buttons – Button1 and Button2. What I want to achieve is in run time when I press Button1, myMediaElement to play Sound1.mp3 and myImage to display Picture1.jpg. When I press Button2, I would like myMediaElement to play Sound2.mp3 and myImage to display Picture2.jpg.

    Within the buttons click event I have to change the source of myMediaElement and myImage and then play and display them respectively, unfortunately without success. In design time both myMediaElement and myImage do not have defined source.

    This appears quite simple, however nobody has contacted me to say how to do it. Does it mean it is not possible?

    Any help would be greatly appreciated.

    Thanks

    Miho Mihov

    Monday, June 16, 2014 12:08 AM

Answers

  • You need to load the new file into a StorageFile, open it for reading, and then set that stream on the MediaElement.SetSource.

    See the XAML media playback sample for a VB example of loading a MediaElement from a file. See the XAML images sample for an example of loading an image.

                Uri uri = new Uri("ms-appx:///assets/sound1.mp3");          
                StorageFile file = await StorageFile.GetFileFromApplicationUriAsyn(uri); 
     
                // Ensure a file was selected 
                if (file != null) 
                { 
                    // Open the selected file and set it as the MediaElement's source 
                    IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read); 
                    myMediaElement.SetSource(stream, file.ContentType); 
                } 

    • Proposed as answer by Dave SmitsMVP Monday, June 16, 2014 6:37 AM
    • Marked as answer by Anne Jing Wednesday, June 25, 2014 9:45 AM
    Monday, June 16, 2014 12:45 AM
    Moderator