在Windows Phone 8中以编程方式下载媒体文件

5
我们的应用是一个基于视频/音频的应用程序,我们已经将所有媒体上传到Windows Azure。
然而,需要方便用户按需下载音频/视频文件,以便他们可以在本地播放。
因此,我需要编写程序来下载音频/视频文件,并将其保存在隔离存储中。
对于每个音频/视频,我们都有Windows Azure媒体文件访问URL。但是,我卡在了下载媒体文件的第一步。
我搜索了谷歌,并阅读了this article,但是对于WebClient,我无法使用DownloadFileAsync函数。
但是,我尝试了它的其他函数DownloadStringAsyn,并且下载的媒体文件是以字符串格式存在的,但不知道如何将其转换为音频(wma)/视频(mp4)格式。请建议我如何继续?是否有其他下载媒体文件的方法?
以下是我使用的示例代码。
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();
    }
2个回答

1
将此保存在您的工具箱中 :)
    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;
    }

你能提供一个完整的例子吗?在调用DownloadFile之后,我该如何将文件保存到独立存储中? - Sebastian

1

要下载二进制数据,请使用[WebClient.OpenReadAsync][1]。您可以使用它来下载字符串数据以外的数据。

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

private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接