Swift MediaPlayer ミュージック検索で取得

概要

ミュージック検索で取得。

example

検索用ベース

import UIKit
import MediaPlayer

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let filter1 = MPMediaPropertyPredicate(value: "BOOWY", forProperty: MPMediaItemPropertyArtist)
        let filterSet = Set([filter1])
        let mPMediaQuery = MPMediaQuery(filterPredicates: filterSet)
        
        if let collections = mPMediaQuery.collections {
            print(MPMediaType.music)
            print(collections.count)
            for collection in collections {
                print("-/\\-")
                print("\(collection.mediaTypes)")
                collection.items[0].toString()
            }
        }
    }

}

extension MPMediaItem {
    func toString() {
        print("MPMediaItem")
        let keys = [MPMediaItemPropertyAlbumTitle,
                    MPMediaItemPropertyAlbumArtist,
                    MPMediaItemPropertyArtist,
                    MPMediaItemPropertyIsCloudItem,
                    MPMediaItemPropertyAlbumTrackNumber,
                    MPMediaItemPropertyAlbumTrackCount,
                    MPMediaItemPropertyPlayCount,
                    MPMediaItemPropertySkipCount,
                    MPMediaItemPropertyTitle,
                    MPMediaItemPropertyUserGrouping]
        for key in keys {
            let value = self.value(forKey: key)
            if let value = value as? Bool {
                print("- Bool \(key):\(value)")
            }
            else if let value = value as? String {
                print("- String \(key):\(value)")
            }
            else if let value = value as? Int {
                print("- Int \(key):\(value)")
            }
        }
    }
}

アーティスト名で検索

MPMediaPropertyPredicateを使用する。

let filter1 = MPMediaPropertyPredicate(value: "BOOWY", forProperty: MPMediaItemPropertyArtist)
let filterSet = Set([filter1])
let mPMediaQuery = MPMediaQuery(filterPredicates: filterSet)

フィルタはAnd条件

アーティスト名2つは検索が0件になる。

let filter1 = MPMediaPropertyPredicate(value: "BOOWY", forProperty: MPMediaItemPropertyArtist)
let filter2 = MPMediaPropertyPredicate(value: "sinon", forProperty: MPMediaItemPropertyArtist)
let filterSet = Set([filter1, filter2])
let mPMediaQuery = MPMediaQuery(filterPredicates: filterSet)

検索結果をアルバム単位にする

groupingTypeを指定。

let filter1 = MPMediaPropertyPredicate(value: "渡辺美里", forProperty: MPMediaItemPropertyArtist)
let filterSet = Set([filter1])
let mPMediaQuery = MPMediaQuery(filterPredicates: filterSet)
mPMediaQuery.groupingType = MPMediaGrouping.album

Swift

Posted by shi-n