簡體   English   中英

在 Swift iOS MPMediaPlayer 應用程序中切換播放列表和設置計時器的問題

[英]Problems switching between playlists and setting timers in Swift iOS MPMediaPlayer app

我正在構建一個音樂播放器應用程序,旨在模仿廣播或互聯網流媒體自動化。 我已經成功地從播放列表中提取音樂並按上次播放日期進行過濾,這樣歌曲就不會經常重復(對我的 iPod 感到非常惱火)。 我希望它每一刻鍾從一個單獨的播放列表中安排播放短電台 ID,然后返回到當前播放列表或切換到一個新的播放列表。 我遇到的障礙是讓重復計時器等待歌曲結束后再播放 ID,並且在切換回音樂之前只播放一個 ID。 通知觀察者……

NotificationCenter.default.addObserver(self, selector:#selector(ViewController.quarterHour), name: NSNotification.Name.MPMusicPlayerControllerNowPlayingItemDidChange, object: nil)

……觸發計時器……

self.timer2 = Timer(fireAt: date, interval: 1, target: self, selector: #selector(ViewController.runVoicer(_:)), userInfo: nil, repeats: true)
self.timer2.tolerance = 0.1
        

...運行此功能:

    @objc func quarterHour() {
        self.timer2 = Timer.scheduledTimer(timeInterval: 900, target: self, selector: #selector(ViewController.runVoicer(_:)), userInfo: nil, repeats: true)
        self.timer2.tolerance = 0.1
        }

從 Voicers 播放列表中選擇的媒體查詢...

    @objc func runVoicer(_:AnyObject) {
        mp.pause()
        let queryVoice = MPMediaQuery.songs()
        let predicate = MPMediaPropertyPredicate(value: "Voicers",
                                                forProperty: MPMediaPlaylistPropertyName,
                                                comparisonType: .equalTo)
        queryVoice.addFilterPredicate(predicate)
        var collection = [MPMediaItem]()
        let unixDefault = Date(timeIntervalSince1970: 100)
        if let voicers = queryVoice.items {
            collection = voicers.sorted{$0.lastPlayedDate ?? unixDefault > $1.lastPlayedDate ?? unixDate}
        }
        let voiceCollection = MPMediaItemCollection(items: collection)
        mp.setQueue(with: voiceCollection)
            mp.play()
        fetchRockPlaylist()
    }

…不僅在計時器關閉時中斷一首歌而不是使用“…NowPlayingItemDidChange”通知,而且還在繼續播放而不是在一次播放后返回底部列出的函數,因為我無法找到任何方法來隔離第一個項目語音集合數組。

更新:沒過多久就意識到計時器方法從未發生過。 動態切換播放列表的固有延遲意味着在 ID 開始之前聽下一首歌曲的一兩秒鍾。 經過幾天的研究,我在 Playground 中取得了突破,即遍歷兩個數組並定期將項目從一個數組插入另一個數組。 因此,在重寫函數以調用兩個播放列表,並根據需要對結果數組進行混洗、排序和過濾后,此循環在每 3 首歌曲之后放置一個 ID……

let arrayCount = voiceCollection.count
var interR = 0
var indexV = 0
// for loop iterates through rock collection by 3, inserts item from voice collection
    for i in 0..<arrayCount {
       rockSet.insert(voiceCollection[indexV], at:interR)
       interR += 4
       indexV += 1
}

現在它完全按照我的意願運行。 剩下的一個問題是確保我的可用歌曲數量至少是 ID 的 3 倍,否則我會遇到超出范圍的錯誤,但這很容易避免。 只是想把它放在那里,以防其他人發現它有用,因為我似乎在其他任何地方都找不到它的例子。 干杯…

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM