简体   繁体   中英

Is it possible to play a Song from iOS Music Library with AVAudioEngine?

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

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:

Where You Create Your MPMediaPickerController

let mediaPicker = MPMediaPickerController(mediaTypes: .anyAudio)
mediaPicker.delegate = self
present(mediaPicker, animated: true, completion: nil)

Delegate Methods

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM