Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading Media File programmatically in Windows Phone 8

Our app is video/audio based app, and we have uploaded all the media on Windows Azure.

However it is required to facilitate user to download audio/video file on demand, so that they can play it locally.

So i need to download audio/video file programmatically and save it in IsolatedStorage.

We have Windows Azure Media File Access URLs for each audio/video. But I am stuck in 1st step of downloading media file.

I googled and came across this article, but for WebClient there is no function DownloadFileAsync that I can use.

However I tried its other function DownloadStringAsyn, and download media file is in string format but don't know how to convert it to audio(wma)/video(mp4) format. Please suggest me, how can I proceed? Is there other way to download media file?

Here is sample code that I used

private void ApplicationBarMenuItem_Click_1(object sender, EventArgs e)
    {
        WebClient mediaWC = new WebClient();
        mediaWC.DownloadProgressChanged += new DownloadProgressChangedEventHandler(mediaWC_DownloadProgressChanged);
        mediaWC.DownloadStringAsync(new Uri(link));            
        mediaWC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(mediaWC_DownloadCompleted);           

    }

    private void mediaWC_DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Cancelled)
            MessageBox.Show("Downloading is cancelled");
        else
        {
            MessageBox.Show("Downloaded");
        }
    }   

    private void mediaWC_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        statusbar.Text = status= e.ProgressPercentage.ToString();
    }
like image 463
Dk358 Avatar asked Nov 04 '22 00:11

Dk358


2 Answers

For downloading binary data, use [WebClient.OpenReadAsync][1]. You can use it to download data other than string data.

var webClient = new WebClient();
webClient.OpenReadCompleted += OnOpenReadCompleted;
webClient.OpenReadAsync(new Uri("...", UriKind.Absolute));

private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{

}
like image 97
Toni Petrina Avatar answered Nov 10 '22 13:11

Toni Petrina


Save this in your toolbox :)

    public static Task<Stream> DownloadFile(Uri url)
    {
        var tcs = new TaskCompletionSource<Stream>();
        var wc = new WebClient();
        wc.OpenReadCompleted += (s, e) =>
        {
            if (e.Error != null) tcs.TrySetException(e.Error);
            else if (e.Cancelled) tcs.TrySetCanceled();
            else tcs.TrySetResult(e.Result);
        };
        wc.OpenReadAsync(url);
        return tcs.Task;
    }
like image 25
Patrick F Avatar answered Nov 10 '22 14:11

Patrick F