PiliPala Player
这次按照作业要求,PiliPala Player增加了在线播放的功能以及下载.mp3或者.mp4到music文件夹两个功能。两个功能的核心我理解为文件流的处理问题。
下面是PiliPala 2.0版本的功能演示。
主页面
在线播放功能要在textbox中输入播放网址,如http://www.neu.edu.cn/indexsource/neusong.mp3,然后点击Play Online
Download的功能也是将目标的网址输入之后,点击Download,此时你的文件就会下载到本地,同样用我挚爱的校歌举例。
然后选择Select File
这样neusong就被下载到本地了。
关于遇到的技术问题
对于在线播放,只需要将原来从 FileOpenPicker 获取的文件源改为网站地址url就可以了。本菜没有在csdn的论坛上找到这类博文,所以直接请教的大神室友。下面是我的代码:
private void Button_Online(object sender, RoutedEventArgs e)
{
mediaplayer.Source = new Uri(URlBox.Text.ToString());
}
然后对于下载到本地的问题
我参考了下面的博文:
https://www.cnblogs.com/T-ARF/p/5886153.html
其代码如下:
HttpClient client = new HttpClient();
using (var musicStream = client.GetStreamAsync("http://dx.sc.chinaz.com/Files/DownLoad/sound1/201207/1771.mp3").Result)
{
int currentPos = 0;
byte[] tempbyte = new byte[4096];
MemoryStream ms = new MemoryStream(4096);
//当遇到0,表示读完了
do
{
currentPos = musicStream.Read(tempbyte, 0, 4096);
ms.Write(tempbyte, 0, currentPos);
} while (currentPos != 0);
File.WriteAllBytes("c:\\test.mp3", ms.ToArray());
System.Console.WriteLine("OK");
}
反正其主要运用httpclient,然后我又找到了一片关于httpclient的博文https://blog.csdn.net/duyelang/article/details/50526213
然后我的相关代码:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
DownloadFile(URlBox.Text);
}
private async void DownloadFile(String Uri)
{
Task t = new Task(() =>
{
try
{
using (HttpClient httpClient = new HttpClient())
{
using (HttpResponseMessage response = httpClient.GetAsync(new Uri(Uri)).Result)
{
var filename = Uri.Split('/');
WriteToFile(filename[filename.Length - 1], response.Content.ReadAsByteArrayAsync().Result);
}
}
}
catch (Exception e)
{
}
});
t.Start();
await t;
}
private async void WriteToFile(string fileName, byte[] file)
{
try
{
StorageFolder folder = KnownFolders.MusicLibrary;
StorageFile f = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (StorageStreamTransaction x = await f.OpenTransactedWriteAsync())
{
using (DataWriter w = new DataWriter(x.Stream))
{
w.WriteBytes(file);
x.Stream.Size = await w.StoreAsync();
await x.CommitAsync();
}
}
}
catch (Exception ex)
{
}
以上就是所有内容,慢慢学习,慢慢探索,越发体会到了uwp的乐趣。期待下次作业。