Uwp——NaiveMediaPlayer2
Github传送门
经过上次的惨痛教训,好吧,尽管这样我也不想直接加一个AreTransportControlsEnabled="True"让这个播放器更美的。
经过一番思考,我非常快的实现了滑块修改音量的功能,没有数据绑定,也没有反人类的按音量之后才能修改音量了,这些智障问题就不提了,不提了。
I 实现通过Url播放网络上的歌曲
第一次做的时候就了解过了,修改source为对应的url就可以了,在第一次的基础上新添了一个按钮
代码如下:
private void Play2_Click(object sender, RoutedEventArgs e)
{
mediaElement.Source = new Uri("http://www.neu.edu.cn/indexsource/neusong.mp3", UriKind.Absolute);
}
同理,当药下载某个页面的MP3文件时,只要输入url或者修改代码中的uri就可以实现,如果再要实现用户手动实现的功能就需要添加TextBox输入文字再传到Uri里……
II 实现下载歌曲保存到本地再播放
核心问题就是怎么把网上的mp3资源(此处)下载到本地,一是资源获取,二是存储地址。通过查资料我知道这里要用到httpclient(下载小型文件)
[HttpClient官方文档](https://docs.microsoft.com/en-us/windows/uwp/networking/httpclient)
参考代码:
//Create an HTTP client object
Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
//Add a user-agent header to the GET request.
var headers = httpClient.DefaultRequestHeaders;
//The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
//especially if the header value is coming from user input.
string header = "ie";
if (!headers.UserAgent.TryParseAdd(header))
{
throw new Exception("Invalid header value: " + header);
}
header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
if (!headers.UserAgent.TryParseAdd(header))
{
throw new Exception("Invalid header value: " + header);
}
Uri requestUri = new Uri("http://www.contoso.com");
//Send the GET request asynchronously and retrieve the response as a string.
Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
string httpResponseBody = "";
try
{
//Send the GET request
httpResponse = await httpClient.GetAsync(requestUri);
httpResponse.EnsureSuccessStatusCode();
httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
}
我的代码:
private async void Download_Click(object sender, RoutedEventArgs e)
{
Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
var buffer = await httpClient.GetBufferAsync(new Uri("http://www.neu.edu.cn/indexsource/neusong.mp3"));
if (buffer == null) return;
//创建本地资源
FileSavePicker fileSavePicker = new FileSavePicker();
fileSavePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
fileSavePicker.FileTypeChoices.Add("校歌", new List<string>() { ".mp3" });
var storageFile = await fileSavePicker.PickSaveFileAsync();
if (storageFile == null) return;
//写入本地资源
CachedFileManager.DeferUpdates(storageFile);
await FileIO.WriteBufferAsync(storageFile, buffer);
await CachedFileManager.CompleteUpdatesAsync(storageFile);
MessageDialog msg = new MessageDialog("Welcome!");//.....
//写入MediaElement
var stream = await storageFile.OpenAsync(FileAccessMode.Read);
mediaElement.SetSource(stream, "");
}
同时还要注意
这里需要勾选音乐库,否则……
代码中还涉及到文件路径的问题,这里作一些解释。
参考Files and folders in the music
StorageFolder testFolder = await StorageFolder.GetFolderFromPathAsync(@"C:\test");
StorageFile sourceFile = await testFolder.GetFileAsync("TestImage.jpg");
StorageFile destinationFile = await KnownFolders.CameraRoll.CreateFileAsync("MyTestImage.jpg");
using (var sourceStream = (await sourceFile.OpenReadAsync()).GetInputStreamAt(0))
{
using (var destinationStream = (await destinationFile.OpenAsync(FileAccessMode.ReadWrite)).GetOutputStreamAt(0))
{
await RandomAccessStream.CopyAndCloseAsync(sourceStream, destinationStream);
}
}
找资料是个技术活,运气好就成了,运气不好就沉了哎。最近有点忙,还要写很多别的作业和项目,就不再多写了吧。