Windows8开发中设置MediaElement音乐资源的几种方法

设置音乐资源总共就两种模式,一种是设置myMediaElement.Source,另一种则是直接使用myMediaElement.SetSource()方法。

我们先看下第一种模式,查看MediaElement的Source属性:

1         //
2         // 摘要:
3         //     获取或设置 MediaElement 上的媒体源。
4         //
5         // 返回结果:
6         //     元素的源,描述统一资源标识符 (URI) 的对象。默认值为 null。
7         public Uri Source { get; set; }

知道了Source是什么类型就可以设置它的值了。

a)设置本地的Source,路径奉上先:ApplicationData.Current.LocalFolder.Path

1 myMediaElement.Source = new Uri(new Uri("ms-appdata:///"), "Local/musicFile.mp3");

b)从网络上获取的歌曲链接:

1 //测试的歌曲链接,不一定好使
2 myMediaElement.Source = new Uri("http://data1.act3.qq.com/2008-09-08/22/a86924ac4463f304e58b470b860bdf88.mp3");

然后就是第二种模式,查看MediaElement的SetSource方法:

 1         //
 2         // 摘要:
 3         //     使用提供的流设置 Source 属性。
 4         //
 5         // 参数:
 6         //   stream:
 7         //     包含要加载的媒体的流。
 8         //
 9         //   mimeType:
10         //     媒体资源的 MIME 类型,表示为通常可在 HTTP 标头和请求中查看的字符串形式。
11         public void SetSource(IRandomAccessStream stream, string mimeType);

知道了SetSource方法的参数类型下面就是添加歌曲

1 //用于选择歌曲文件
2 FileOpenPicker openMusicFile = new FileOpenPicker();
3 StorageFile musicFile = await openMusicFile.PickSingleFileAsync();
4 IRandomAccessStream stream = await musicFile.OpenAsync(FileAccessMode.Read);
5 myMediaElement.SetSource(stream, musicFile.ContentType);

上面是添加单个的歌曲文件,也可以添加一次性添加多个:这时候就可以定义如下变量:

List<IRandomAccessStream> streamList;

IReadOnlyList<StorageFile> muiscFileList;

myMediaElement.SetSource(streamList[i], musicFileList[i].ContentType);

上面就是几种常用的设置歌曲源的方法,如有不明白的请联系作者:269592511@qq.com

posted @ 2013-05-11 12:15  Jonefriend  阅读(292)  评论(0编辑  收藏  举报