Apple Music& Swift中的AVAudioEngine

时间:2016-03-23 00:42:25

标签: swift avaudioengine apple-music

iOS 9.3发布,Apple Music提供了使用MPMusicPlayerController播放音乐的权限......但

有谁知道如何访问Apple Music库以播放AVAudioPlayerNode的内容 - > AVAudioEngine用于音频处理?

我在Apple forum中提出了这个问题。 谁对此问题感兴趣 - 请在论坛中支持。

1 个答案:

答案 0 :(得分:0)

  1. NSAppleMusicUsageDescription键添加到Info.plist文件及其相应的值
  2. 设置AVAudioSession和`AVAudioEngine
  3. 找到您要播放的媒体项目的URL(您可以像下面的示例一样使用MPMediaPickerController,也可以制作自己的MPMediaQuery
  4. 从该URL创建一个AVAudioFile
  5. 创建一个AVAudioPlayerNode集来播放AVAudioFile
  6. 将播放器节点连接到引擎的输出节点
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)
    }
}