swift xcode 从播放器列表中播放声音文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26124062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
swift xcode play sound files from player list
提问by rpw
I am looking for a swift coding playing sound out of the player list and not sounds added as resource to your project. I mainly found the usage of NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound_name", ofType: "wav")) println(alertSound) but for this you need to have the sound file in your bundle. But I couldn't find any example selecting audio files bought thru itunes and play them.
我正在寻找播放器列表中播放声音的快速编码,而不是将声音作为资源添加到您的项目中。我主要发现了 NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound_name", ofType: "wav")) println(alertSound) 的用法,但为此你需要在你的包中包含声音文件。但是我找不到任何选择通过 iTunes 购买的音频文件并播放它们的示例。
Any idea how to do this? Can I access my music layer playlist files and using them in my app?
知道如何做到这一点吗?我可以访问我的音乐层播放列表文件并在我的应用程序中使用它们吗?
Thanks for any code lines. rpw
感谢您提供任何代码行。净水器
回答by Eduardo Lino
These music files are represented by MPMediaItem instances. To fetch them, you could use an MPMediaQuery, as follows:
这些音乐文件由 MPMediaItem 实例表示。要获取它们,您可以使用MPMediaQuery,如下所示:
let mediaItems = MPMediaQuery.songsQuery().items
At this point, you have all songs included in Music App Library, so you can play them with a MPMusicPlayerControllerafter setting a playlist queue:
此时,您已将所有歌曲包含在音乐应用程序库中,因此您可以在设置播放列表队列后使用MPMusicPlayerController播放它们:
let mediaCollection = MPMediaItemCollection(items: mediaItems)
let player = MPMusicPlayerController.iPodMusicPlayer()
player.setQueueWithItemCollection(mediaCollection)
player.play()
You might need to filter songs by genre, artist, album and so on. In that case, you should apply a predicate to the query before fetching the media items:
您可能需要按流派、艺术家、专辑等过滤歌曲。在这种情况下,您应该在获取媒体项之前将谓词应用于查询:
var query = MPMediaQuery.songsQuery()
let predicateByGenre = MPMediaPropertyPredicate(value: "Rock", forProperty: MPMediaItemPropertyGenre)
query.filterPredicates = NSSet(object: predicateByGenre)
let mediaCollection = MPMediaItemCollection(items: query.items)
let player = MPMusicPlayerController.iPodMusicPlayer()
player.setQueueWithItemCollection(mediaCollection)
player.play()
Cheers!
干杯!