[Solved] How could I select music files in iOS app [closed]


See if below code works for you,

Add ‘NSAppleMusicUsageDescription’ to your Info.plist for the privacy authority.
Make sure your music is available in your iPhone. It will not work in the simulator.

import UIKit
import AVFoundation
import MediaPlayer

class ViewController: UIViewController, MPMediaPickerControllerDelegate {

    var musicPlayer: AVAudioPlayer?
    var pickerVC: MPMediaPickerController?
    var mediaItems = [MPMediaItem]()
    let currentIndex = 0

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool){

    }

    func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
        mediaItems = mediaItemCollection.items
        updatePlayer()
        self.dismiss(animated: true, completion: nil)
    }

    func updatePlayer(){
        let item = mediaItems[currentIndex]
        if let path: NSURL = item.assetURL as NSURL? {
            do {
                musicPlayer = try AVAudioPlayer(contentsOf: path as URL)
                musicPlayer?.enableRate = true
                musicPlayer?.rate = 1.0
                musicPlayer?.numberOfLoops = 0
                musicPlayer?.currentTime = 0
            } catch {
                musicPlayer = nil
            }
        }
    }

    @IBAction func play(_ sender: AnyObject) {
        //AVMusicPlayer.deviceCurrentTime
        musicPlayer?.play()
    }

    @IBAction func stop(_ sender: AnyObject) {
        musicPlayer?.stop()
    }

    @IBAction func picker(_ sender: AnyObject) {
        pickerVC = MPMediaPickerController(mediaTypes: .music)
        pickerVC?.allowsPickingMultipleItems = false
        pickerVC?.delegate = self
        if let controller = pickerVC {
            present(controller, animated: true, completion: nil)
        }
    }
}

1

solved How could I select music files in iOS app [closed]