{ Learn Code. Share Code. Teach Code. Love Code. }

  • Playing Sound & Video

  • Visual Basic tutorials for UWP apps.
Visual Basic tutorials for UWP apps.
 #70759  by CodenStuff
 Sat Aug 11, 2012 5:09 pm
Sound and Video

You can play sound or video in two different ways the first by using a MediaElement control in XAML just like this:
Code: Select all
<MediaElement x:Name="BoomBox" Margin="0" Source="NameOfMediaFile.ext" />
After adding the MediaElement you can adjust it size, location using properties and set other options such as media source file, playback speed, auto play, looping and volume. You can access the MediaElement via code but you need to give it a name first I gave this one the name 'BoomBox' and you can control it in your code like this:
Code: Select all
        BoomBox.IsLooping = True
        BoomBox.Volume = 1
All properties are accessible via code.

The other way of playing sound or video is by creating a media element in code like this:
Code: Select all
        Dim BoomBox As MediaElement = New MediaElement()
        Dim BBFolder As StorageFolder = Await Package.Current.InstalledLocation.GetFolderAsync("FolderName")
        Dim BBFile As StorageFile = Await BBFolder.GetFileAsync("NameOfMediaFile.ext")
        Dim BBStream = Await BBFile.OpenAsync(FileAccessMode.Read)
        BoomBox.Volume = 1
        BoomBox.SetSource(BBStream, BBFile.ContentType)
I had some trouble with the volume option in that code as it didn't seem to be working correctly the first few times I tried it and I then realised that you had to set the volume before setting the source to make it work - very odd lol

The volume property on both goes from 0 to 1 where 0 is the no sound and 1 is maximum volume level 0.5 would be in the middle.

Basic simple and useful for adding background music, sound fx and video into your apps.