gpt4 book ai didi

mpmediaplayercontroller - 无法使用 MPMusicPlayerMediaItemQueueDescriptor 设置 MPMusicPlayerController 队列

转载 作者:行者123 更新时间:2023-11-30 11:24:49 25 4
gpt4 key购买 nike

此代码导致沉默:

let query = MPMediaQuery.songs()
let result = query.items
guard let items = result, items.count > 0 else {return}
let song = items[0]

let player = MPMusicPlayerController.applicationQueuePlayer

let coll = MPMediaItemCollection(items: [song])
let q = MPMusicPlayerMediaItemQueueDescriptor(itemCollection: coll)
player.setQueue(with: q)
player.play()

我已经单步执行了代码,我们到达了player.play()。我有一个 MPMediaItem,并且我已经正确地从中形成了 MPMediaItemCollection,并从那个中形成了 MPMusicPlayerMediaItemQueueDescriptor。那么为什么我的玩家不玩呢?

最佳答案

swift 5

我来晚了一点,但这就是我的想法。 (我正在修剪歌曲以使用描述符进行播放)。

确保在主线程上运行音乐播放器的所有内容。否则你会遇到奇怪的错误。

通过permanentId获取歌曲:

/// Retrieves a song in the MPMediaItem format using the persistentId passed.
/// - Parameter persistentID: (UInt64) The songs persistentId.
/// - Returns: (MPMediaItem?) Nil if not found other wise the MPMediaItem (song).
private static func getSong(forId persistentID: UInt64) -> MPMediaItem? {
let query = MPMediaQuery.songs()
let predicate = MPMediaPropertyPredicate(value: persistentID, forProperty: MPMediaItemPropertyPersistentID)
query.addFilterPredicate(predicate)
return query.items?.first
}

通过permanentId播放歌曲:

private var startTime: Double = 0
private var endTime: Double = 0


/// Plays the song with the identifier.
/// - Note: Trims song to start and end time.
/// - Parameter persistentId: (UInt64) The song persistent identifier.
private func play(forId persistentId: UInt64) {
DispatchQueue.main.async {
if let song = Self.getSong(forId: persistentId) {
let identifier = MPMediaItemPropertyPersistentID
let predicate = MPMediaPropertyPredicate(value: persistentId, forProperty: identifier)
let query = MPMediaQuery(filterPredicates: [predicate])
let descriptor = MPMusicPlayerMediaItemQueueDescriptor(query: query)
descriptor.setStartTime(self.startTime, for: song)
descriptor.setEndTime(self.endTime, for: song)
self.musicPlayer.setQueue(with: descriptor)
self.musicPlayer.prepareToPlay()
self.musicPlayer.repeatMode = .none
self.musicPlayer.play()
}
}
}

我还发现初始化音乐 Controller 的方式很重要:

private lazy var musicPlayer: MPMusicPlayerController = { MPMusicPlayerController.applicationQueuePlayer }()

请注意:某些代码不可拖放。您需要定义诸如开始和结束时间变量之类的内容。

关于mpmediaplayercontroller - 无法使用 MPMusicPlayerMediaItemQueueDescriptor 设置 MPMusicPlayerController 队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50864171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com