WP8.1 和UWP 如何使用下载网页的上的音频 并保存

时间:2024-08-29 14:33:38

WP8.1:

 private   async   Task<StorageFile>  GetVoiceData()
{ HttpClient httpclient = new HttpClient();
var GetData = await httpclient.GetStreamAsync(new Uri("http://dx.sc.chinaz.com/Files/DownLoad/sound1/201207/1771.mp3"));
var file = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync("1771.mp3", CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenStreamForWriteAsync())
{
await GetData.CopyToAsync(stream);//将获取的HttpClient的Stream流复制到文件的stream流
await stream.FlushAsync();//异步刷新 } return This_Voice_files;
}
}

UWP:

public async Task<StorageFile> Load()
{
try
{
var httpClient = new HttpClient();
var buffer = await httpClient.GetBufferAsync(new Uri("http://dx.sc.chinaz.com/Files/DownLoad/sound1/201207/1771.mp3"));
if (buffer != null && buffer.Length > 0u)
{
var file = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync("1771.mp3", CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await stream.WriteAsync(buffer);
await stream.FlushAsync();
}
return file;
}
}
catch { }
return null;
}

C#:

HttpClient client = new HttpClient();
using (var musicStream = client.GetStreamAsync("http://dx.sc.chinaz.com/Files/DownLoad/sound1/201207/1771.mp3").Result)
{
int currentPos = ;
byte[] tempbyte = new byte[]; MemoryStream ms = new MemoryStream();
//当遇到0,表示读完了
do
{
currentPos = musicStream.Read(tempbyte, , );
ms.Write(tempbyte, , currentPos);
} while (currentPos != );
File.WriteAllBytes("c:\\test.mp3", ms.ToArray());
System.Console.WriteLine("OK");
}