iOS 9.3发布,Apple Music提供了使用MPMusicPlayerController播放音乐的权限......但
有谁知道如何访问Apple Music库以播放AVAudioPlayerNode的内容 - > AVAudioEngine用于音频处理?
我在Apple forum中提出了这个问题。 谁对此问题感兴趣 - 请在论坛中支持。
答案 0 :(得分:0)
NSAppleMusicUsageDescription
键添加到Info.plist文件及其相应的值AVAudioSession
和`AVAudioEngine MPMediaPickerController
,也可以制作自己的MPMediaQuery
)AVAudioFile
AVAudioPlayerNode
集来播放AVAudioFile
import UIKit
import AVFoundation
import MediaPlayer
class ViewController: UIViewController {
let engine = AVAudioEngine()
override func viewDidLoad() {
super.viewDidLoad()
let mediaPicker = MPMediaPickerController(mediaTypes: .music)
mediaPicker.allowsPickingMultipleItems = false
mediaPicker.showsCloudItems = false // you won't be able to fetch the URL for media items stored in the cloud
mediaPicker.delegate = self
mediaPicker.prompt = "Pick a track"
present(mediaPicker, animated: true, completion: nil)
}
func startEngine(playFileAt: URL) {
do {
try AVAudioSession.sharedInstance().setCategory(.playback)
let avAudioFile = try AVAudioFile(forReading: playFileAt)
let player = AVAudioPlayerNode()
engine.attach(player)
engine.connect(player, to: engine.mainMixerNode, format: avAudioFile.processingFormat)
try engine.start()
player.scheduleFile(avAudioFile, at: nil, completionHandler: nil)
player.play()
} catch {
assertionFailure(String(describing: error))
}
}
}
extension ViewController: MPMediaPickerControllerDelegate {
func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
guard let item = mediaItemCollection.items.first else {
print("no item")
return
}
print("picking \(item.title!)")
guard let url = item.assetURL else {
return print("no url")
}
dismiss(animated: true) { [weak self] in
self?.startEngine(playFileAt: url)
}
}
func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) {
dismiss(animated: true, completion: nil)
}
}