本文阐述如何在WindowsPhone 8 中下载网络音频,并保存到独立存储空间中。实现在无网络的情况下能够后台播放此音频文件。
直接进入主题:
1、新建解决方案:PlayIsolatedStorageMusicDemo。
2、在解决方案中添加一个“WindowPhone音频播放代理”项目:MyAudioPlaybackAgent
3、在项目“PlayIsolatedStorageMusicDemo”中添加对项目“MyAudioPlaybackAgent”的引用
解决方案资源管理器目录结构如图所示:
4、在MainPage.xaml文件中进行简单布局,未下载完成前“移动”和“播放”按钮不可用;使用一个ProgressBar显示下载进度(由于只是个简单的
Demo,所以这里的XAML页面布局就简单一点),如图
5、下载按钮添加DownLoad_Click事件:
private BackgroundTransferRequest _request; private string downloadPath; private void DownLoad_Click(object sender, RoutedEventArgs e) { // 传输的文件网络路径 Uri requestUri; try { requestUri = new Uri(fileUrl.Text, UriKind.RelativeOrAbsolute); } catch { MessageBox.Show("文件地址不符合格式"); return; } //设置文件下载地址 downloadPath = string.Format("shared/transfers/{0}.mp3", Guid.NewGuid()); //创建一个后台文件传输请求 _request = new BackgroundTransferRequest( requestUri) { Method = "GET",// 设置传输的方法为GET请求 DownloadLocation = new Uri(downloadPath, UriKind.Relative), Tag = "something else", //添加请求的Tag属性,Tag属性不能超过4000个字符 TransferPreferences = TransferPreferences.AllowBattery }; _request.TransferStatusChanged += _request_TransferStatusChanged; _request.TransferProgressChanged += _request_TransferProgressChanged; // 使用BackgroundTransferService添加文件传输请求 try { BackgroundTransferService.Add(_request); } catch (Exception ex) { MessageBox.Show("无法添加请求:" + ex.Message); } }
其中:
void _request_TransferStatusChanged(object sender, BackgroundTransferEventArgs e) { if (e.Request.TransferStatus == TransferStatus.Completed) { if (e.Request.StatusCode == 200 || e.Request.StatusCode==206) { btnMove.IsEnabled = true; //to do something else } } } void _request_TransferProgressChanged(object sender, BackgroundTransferEventArgs e) { Bar.Value = _request.BytesReceived*100/_request.TotalBytesToReceive; }
string fileName; private void btnMove_Click(object sender, RoutedEventArgs e) { fileName = downloadPath.Split(new char[] { '/' }, StringSplitOptions.None)[2]; using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { if (storage.FileExists(downloadPath)) { storage.MoveFile(downloadPath, fileName); btnPlay.IsEnabled = true; } } }
private void btnPlay_Click(object sender, RoutedEventArgs e) { AudioTrack _audioTrack = new AudioTrack(new Uri(fileName, UriKind.Relative),"歌曲名", "艺术家", "专辑", null); BackgroundAudioPlayer.Instance.Track = _audioTrack; BackgroundAudioPlayer.Instance.Play(); }
8、运行程序。输入音频文件下载地址,即可实现下载网络音频,并在后台播放下载完成的音频文件
9、一些说明: