Click here to Skip to main content
14,027,303 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

8.5K views
1 bookmarked
Posted 15 Jun 2015
Licenced CPOL

Azure: Upload and Stream Video Content to WPF from Blob Storage

, 15 Jun 2015
Rate this:
Please Sign up or sign in to vote.
Azure: how to upload and stream video content to WPF from blob storage

A while back when Azure first came out, I toyed with the idea of uploading video content to Azure Blob Storage, and having it play back in my WPF app. At the time (can’t recall exactly when that was, but quite a while ago), I had some major headaches doing this. The problem stemmed from the fact that the WPF MediaElement and the Azure Blob Storage did not play nicely together.

You just could not seek (that is when you go to an unbuffered / not downloaded) to a segment of the video and try and play. It just did not work, you would have to wait for the video to download ALL the content up the point you requested.

There is a very good post that discusses this old problem here.

Previously, you had to set the Blob storage API version. Starting from the 2011-08-18 version, you can do partial and pause/resume downloads on blob objects. The nice thing is that your client code doesn’t have to change to achieve this. 

Luckily, this is no longer a problem, so nowadays, it is as simple as following these steps:

  1. Upload a video (say MP4) to Azure Blob Storage
  2. Grab the URI of the uploaded video
  3. Use that URI for a WPF MediaElement

I have created a small demo app here for you, here is what it looks like after I uploaded a video and pressed the play button.

The code is dead simple, here is the XAML (it's a WPF app):

<Window x:Class="WpfMediaPlayerFromBlobstorage.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="350" Width="525" WindowState="Maximized">
    <Grid>
        <DockPanel LastChildFill="True">
            
            <StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
                <Button x:Name="btnUpload"

                        Click="BtnUpload_OnClick"

                        Content="Pick MP4 file to upload"

                        Width="Auto"

                        Margin="5"

                        Height="23"/>
                <StackPanel Orientation="Horizontal" Margin="50,5,5,5">
                    <StackPanel x:Name="controls"

                                HorizontalAlignment="Center"

                                Orientation="Horizontal">
 
                        <Button x:Name="btnPlay"

                                Height="23"

                                Content="Play"

                                VerticalAlignment="Center"

                                Margin="5"

                                Click="BtnPlay_OnClick" />
                        <Button x:Name="btnPause"

                                Height="23"

                                Content="Pause"

                                VerticalAlignment="Center"

                                Margin="5"

                                Click="BtnPause_OnClick" />
                        <Button x:Name="btnStop"

                                Height="23"

                                Content="Stop"

                                VerticalAlignment="Center"

                                Click="BtnStop_OnClick"

                                Margin="5" />
 
                        <TextBlock VerticalAlignment="Center"

                                   Text="Seek To"

                                   Margin="5" />
                        <Slider Name="timelineSlider"

                                Margin="5"

                                Height="23"

                                VerticalAlignment="Center"

                                Width="70"

                                ValueChanged="SeekToMediaPosition" />
 
                    </StackPanel>
                </StackPanel>
            </StackPanel>
            <MediaElement x:Name="player"

                          Volume="1"

                          LoadedBehavior="Manual"

                          UnloadedBehavior="Manual"

                          HorizontalAlignment="Stretch"

                          VerticalAlignment="Stretch"

                          Margin="10"

                          MediaOpened="Element_MediaOpened"

                          MediaEnded="Element_MediaEnded"/>
        </DockPanel>
    </Grid>
</Window>

And here is the code behind (for simplicity, I did not use MVVM for this demo).

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
 
using Microsoft.Win32;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
 
namespace WpfMediaPlayerFromBlobstorage
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private static string blobStorageConnectionString =
            "DefaultEndpointsProtocol=http;AccountName=YOUR_ACCOUNT_HERE;AccountKey=YOUR_KEY_HERE";
        private Uri uploadedBlobUri=null;
 
 
        public MainWindow()
        {
            InitializeComponent();
            this.controls.IsEnabled = false;
        }
 
        private async void BtnUpload_OnClick(object sender, RoutedEventArgs e)
        {
            this.controls.IsEnabled = false;
            OpenFileDialog fd = new OpenFileDialog();
            fd.InitialDirectory=@"c:\";
            var result = fd.ShowDialog();
            if (result.HasValue && result.Value)
            {
                try
                {
                    var storageAccount = CloudStorageAccount.Parse(blobStorageConnectionString);
                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
                    container.CreateIfNotExists();
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
                    container.SetPermissions(
                        new BlobContainerPermissions
                        {
                            PublicAccess =
                                BlobContainerPublicAccessType.Blob
                        }
                    );
 
                    using (var fileStream = File.OpenRead(fd.FileName))
                    {
                        await blockBlob.UploadFromStreamAsync(fileStream);
                        uploadedBlobUri = blockBlob.Uri;
                        this.controls.IsEnabled = true;
                        MessageBox.Show("File uploaded ok");
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show("Ooops : " + exception.Message);
                }
            }            
        }
 
        private void BtnPlay_OnClick(object sender, RoutedEventArgs e)
        {
            player.Source = uploadedBlobUri;
            player.Play();
            timelineSlider.Value = 0;
        }
 
        private void BtnPause_OnClick(object sender, RoutedEventArgs e)
        {
            player.Pause();
        }
 
        private void BtnStop_OnClick(object sender, RoutedEventArgs e)
        {
            player.Stop();
            timelineSlider.Value = 0;
        }
 
        private void Element_MediaOpened(object sender, EventArgs e)
        {
            timelineSlider.Maximum = player.NaturalDuration.TimeSpan.TotalMilliseconds;
        }
 
        private void Element_MediaEnded(object sender, EventArgs e)
        {
            player.Stop();
            timelineSlider.Value = 0;
        } 
 
        private void SeekToMediaPosition(object sender, 
        RoutedPropertyChangedEventArgs<double> args)
        {
            int sliderValue = (int)timelineSlider.Value;
            TimeSpan ts = new TimeSpan(0, 0, 0, 0, sliderValue);
            player.Position = ts;
        }
    }
}

And there you have it, a very simple media player that allows play/pause/stop and seek from a Azure Blob Storage uploaded video.

You can grab this project (you will need to fill in the Azure Blob Storage connection string details with your own account settings) from my github account here.

NOTE: If you want more control over encoding/streaming, etc., you should check out Azure Media Services.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sacha Barber
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2016
  • Codeproject MVP 2016
  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

You may also be interested in...

Pro

Comments and Discussions

 
QuestionNullReferenceException at player.Play() Pin
R_C_K13-Mar-19 8:55
memberR_C_K13-Mar-19 8:55 
Hi,

I am trying to run your code, because it seems like an ideal solution for a streaming video setup that I want to build. The upload process works perfectly, but when I click the Play button the tool throws a NullReferenceException.

I have not made any changes to your code, other than specifying my own storage connection string and blob names. My DefaultEndpointsProtocol value is https, rather than http like your example. Could that be causing this issue?

Thanks!
Ross

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190419.4 | Last Updated 15 Jun 2015
Article Copyright 2015 by Sacha Barber
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid