iOS
MPMediaPickerDelegate
Buscar..
Observaciones
Consulte la documentación de Apple para obtener más información sobre la privacidad.
Asegúrese de que la aplicación de música esté disponible en su iPhone. No funcionará en el simulador.
Cargue música con MPMediaPickerControllerDelegate y reprodúzcalo con AVAudioPlayer
Ir a través de los pasos:
- Agregue 'NSAppleMusicUsageDescription' a su Info.plist para la autoridad de privacidad.
- Asegúrate de que tu música esté disponible en tu iPhone. No funcionará en el simulador.
iOS 10.0.1
import UIKit
import AVFoundation
import MediaPlayer
class ViewController: UIViewController, MPMediaPickerControllerDelegate {
var avMusicPlayer: AVAudioPlayer!
var mpMediapicker: MPMediaPickerController!
var mediaItems = [MPMediaItem]()
let currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool){
//What to do?
}
func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
mediaItems = mediaItemCollection.items
updatePlayer()
self.dismiss(animated: true, completion: nil)
}
func updatePlayer(){
let item = mediaItems[currentIndex]
// DO-TRY-CATCH try to setup AVAudioPlayer with the path, if successful, sets up the AVMusicPlayer, and song values.
if let path: NSURL = item.assetURL as NSURL? {
do
{
avMusicPlayer = try AVAudioPlayer(contentsOf: path as URL)
avMusicPlayer.enableRate = true
avMusicPlayer.rate = 1.0
avMusicPlayer.numberOfLoops = 0
avMusicPlayer.currentTime = 0
}
catch
{
avMusicPlayer = nil
}
}
}
@IBAction func Play(_ sender: AnyObject) {
//AVMusicPlayer.deviceCurrentTime
avMusicPlayer.play()
}
@IBAction func Stop(_ sender: AnyObject) {
avMusicPlayer.stop()
}
@IBAction func picker(_ sender: AnyObject) {
mpMediapicker = MPMediaPickerController.self(mediaTypes:MPMediaType.music)
mpMediapicker.allowsPickingMultipleItems = false
mpMediapicker.delegate = self
self.present(mpMediapicker, animated: true, completion: nil)
}
}
Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow