天天看點

一個可以緩存的音樂播放器

這次沒有接着上次的做,主要是因為上次那個做的有點醜,不忍直視了。。

這次做一個可以緩存的音樂播放器

緩存的呢是NEU的校歌,其實想想很簡單,就是主要擷取URL的過程,擷取URL的方法,我在文檔中找到了

一個可以緩存的音樂播放器

在這個mediaelement類中對各種空間有着很詳細的介紹

那麼我們就直接說了,、

private void LoadMediaFromString(string path)

        {

            try

            {

                media123.Source = MediaSource.CreateFromUri(new Uri(path));

            }

            catch (Exception ex)

            {

                if (ex is FormatException)

                {

                    // handle exception. 

                    // For example: Log error or notify user problem with file

                }

            }

        }

我們通過一個MediaSource.CreateFromUri(new Uri(path));來擷取一個位址,這樣就能夠實作網絡播放

然後緩存到本地要怎麼解決?

private void DoenLoad_Click(object sender, RoutedEventArgs e)

        {

            media123.Source = MediaSource.CreateFromUri(new Uri(txtFilePath.Text));

            //  Debug.WriteLine(KnownFolders.MusicLibrary.); // 路徑位置

            using (HttpClient httpClient = new HttpClient())

            {

                using (HttpResponseMessage response = httpClient.GetAsync(new Uri(txtFilePath.Text)).Result)

                {

                    var filename = txtFilePath.Text.Split('/');

                    Write(filename[filename.Length - 1], response.Content.ReadAsByteArrayAsync().Result);

                }

            }

        }

一個可以緩存的音樂播放器

其實,我們就是仿照檔案打開的方式,做緩存的,然後還有最重要的就是httpclient這個類

這個擷取方法很像爬蟲,老師上課的時候講過,大家可以用當時做json web service那個樣例程式來做榜樣就行了。

然後就是和上面相輔相成的寫了,有讀檔案就有寫檔案

private async void Write(string fileName, byte[] html)

        {

            try

            {

                StorageFolder folder = KnownFolders.MusicLibrary;

                StorageFile a = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                using (StorageStreamTransaction x = await a.OpenTransactedWriteAsync())

                {

                    using (DataWriter w = new DataWriter(x.Stream))

                    {

                        w.WriteBytes(html);

                        x.Stream.Size = await w.StoreAsync();

                        await x.CommitAsync();

                    }

                }

            }

            catch (Exception ex)

            {

                Debug.WriteLine(ex);

            }

        }

    }

我的代碼是這樣的

然後附上github:https://github.com/656756130/media123

不多放圖了,csdn還要過稽核

UWP