这次没有接着上次的做,主要是因为上次那个做的有点丑,不忍直视了。。

这次做一个可以缓存的音乐播放器

缓存的呢是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还要过审核

相关文章:

  • 2022-12-23
  • 2021-06-26
  • 2021-07-30
  • 2021-09-10
猜你喜欢
  • 2021-11-11
  • 2021-11-24
  • 2021-06-07
  • 2021-11-19
相关资源
相似解决方案