在Swift中用AVPlayer播放歌曲

时间:2015-08-28 01:17:19

标签: ios swift avplayer

如何使用AVPlayer播放歌曲?这是我的代码。

    let song = filteredMusic[indexPath.row]
    let query = MPMediaQuery.songsQuery()
    let isPresent = MPMediaPropertyPredicate(value: song, forProperty: MPMediaItemPropertyTitle, comparisonType: .EqualTo)
    query.addFilterPredicate(isPresent)

    let result = query.items //only going to be one song

    if result!.count == 0 {
        print("not found")
        return
    }

    let url = result![0].assetURL // for some reason this is nil

    let item = AVPlayerItem(URL: url!)

    let player = AVPlayer(playerItem: item)
    player.play()

资产网址为零。怎么样?

2 个答案:

答案 0 :(得分:1)

感谢NKushwah的帮助!我出于几个原因发布了自己的答案。

    let song = filteredMusic[indexPath.row]
    let query = MPMediaQuery.songsQuery()
    let isPresent = MPMediaPropertyPredicate(value: song, forProperty: MPMediaItemPropertyTitle, comparisonType: .EqualTo)
    query.addFilterPredicate(isPresent)

    let result = query.collections

    if result!.count == 0 {
        print("not found")
        return
    }


    let controller = MPMusicPlayerController.systemMusicPlayer()
    let item = result![0]

    controller.setQueueWithItemCollection(item)
    controller.prepareToPlay()
    controller.play()
}
  1. iPodMusicPlayer已被弃用!我改为使用systemMusicPlayer
  2. 我的回答是在Swift。

答案 1 :(得分:0)

有些MPMediaItelm只有他们的内容而不是URl,所以要玩这些你必须使用MPMusicPlayerController -

MPMusicPlayerController *controller = [MPMusicPlayerController iPodMusicPlayer];

MPMediaItem *item = result![0];

[controller setQueueWithItemCollection:collection];
[controller setNowPlayingItem:item];

[controller prepareToPlay];
[controller play];

applicationMusicPlayer不支持背景音乐。请改用MPMusicPlayerController' iPodMusicPlayer。它与内置的iPod播放器共享状态,当您的应用程序进入后台时,音乐将继续播放。