Reputation: 395
i have succesfully created a AVAudioEngine
. It plays local sound-files from the project-directory. But how can I get access to the Music Library on the phone?
Is there a way I can combine AVAudioEngine
with the MPMediaPickerController
?
Thank you
Upvotes: 3
Views: 784
Reputation: 6876
Yes :)
You need to set the MPMediaPickerControllerDelegate
on your MPMediaPickerController
so you will get notified when the user does something in the MPMediaPickerController
. Here are the methods you can use on MPMediaPickerControllerDelegate
.
As you can see, there is the method mediaPicker(_:didPickMediaItems:)
which is called when the user has picked a song to play. That gives you a (MPMediaItemCollection
) which has items
containing the songs which the user picked.
You can loop through that collection and look at the individual items
which are of type MPMediaItem
.
Finally each MPMediaItem
has an assetURL
which you can to create the individual nodes in your AVAudioEngine
.
So...something along the lines of:
let mediaPicker = MPMediaPickerController(mediaTypes: .anyAudio)
mediaPicker.delegate = self
present(mediaPicker, animated: true, completion: nil)
public func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
for item in mediaItemCollection.items {
if let assetURL = item.assetURL {
//There you go :)
}
}
}
Remember to dismiss
the MPMediaPickerController
when done with it (and remember to do so when canceling too (there is a delegate method for that too)).
Hope that points you in the right direction.
Upvotes: 2