Uwp——NaiveMediaPlayer2
Github傳送門
? ? ? ?經(jīng)過上次的慘痛教訓而晒,好吧状蜗,盡管這樣我也不想直接加一個AreTransportControlsEnabled="True"讓這個播放器更美的谦秧。
? ? ? ?經(jīng)過一番思考猖腕,我非尘迹快的實現(xiàn)了滑塊修改音量的功能行楞,沒有數(shù)據(jù)綁定爬迟,也沒有反人類的按音量之后才能修改音量了剩瓶,這些智障問題就不提了番刊,不提了戚揭。
I 實現(xiàn)通過Url播放網(wǎng)絡上的歌曲
? ? ? ?第一次做的時候就了解過了,修改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就可以實現(xiàn)锄禽,如果再要實現(xiàn)用戶手動實現(xiàn)的功能就需要添加TextBox輸入文字再傳到Uri里……
II 實現(xiàn)下載歌曲保存到本地再播放
? ? ? ?核心問題就是怎么把網(wǎng)上的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;
//創(chuàng)建本地資源
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);
}
}
? ? ? ?找資料是個技術活,運氣好就成了维雇,運氣不好就沉了哎淤刃。最近有點忙,還要寫很多別的作業(yè)和項目吱型,就不再多寫了吧逸贾。