直接下载mp3文件

时间:2014-03-11 17:42:27

标签: c# xamarin.android xamarin

我已经使用xamarin一段时间了,我正在处理的当前项目需要下载一些mp3文件。

我看到了下载文件和下载图片的教程,但他们并没有带我到任何地方,而是为了iOS。

给定网址www.xyz.com/music.mp3,如何下载mp3文件并保存?

2 个答案:

答案 0 :(得分:3)

最简单的方法是使用WebClient,如果在UI线程上,则调用方法DownloadFileTaskAsync:

        button.Click += async delegate
        {
            var destination = Path.Combine(
                System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.ApplicationData),
                    "music.mp3");

            await new WebClient().DownloadFileTaskAsync(
                new Uri("http://www.xyz.com/music.mp3"),
                destination);
        };

答案 1 :(得分:2)

Xamarin.iOS Docs转换为下载字节

从下载字符串到下载字节(注意DownloadDataAsyncDownloadDataCompleted vs String兄弟函数)后,Xamarin.iOS docs WebClient sample for downloading a file应该可以正常工作。

var webClient = new WebClient();
webClient.DownloadDataCompleted += (s, e) => {
    var text = e.Result; // get the downloaded text
    string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
    string localFilename = "downloaded.mp3";
    string localPath = Path.Combine (documentsPath, localFilename);
    File.WriteAllText (localpath, text); // writes to local storage   
};
var url = new Uri("http://url.to.some/file.mp3"); // give this an actual URI to an MP3
webClient.DownloadDataAsync(url);

使用HttpClient

如果您想使用较新的HttpClient库。在{Xamarin.Android项目中添加对System.Net.Http的引用,并给出类似的内容。

var url = new Uri("http://url.to.some/file.mp3");
var httpClient = new HttpClient ();
httpClient.GetByteArrayAsync(url).ContinueWith(data => {
    string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
    string localFilename = "downloaded.mp3";
    string localPath = Path.Combine (documentsPath, localFilename);
    File.WriteAllBytes (localPath, data.Result);
});