import UIKit
import MediaPlayer
class ViewController: UIViewController ,MPMediaPickerControllerDelegate{//需要包含MPMediaPickerControllerDelegate
var picker:MPMediaPickerController! //定义选择器
var player:MPMusicPlayerController! //定义播放歌曲
@IBAction func SelectMusicbtn(sender: AnyObject) {
//呈现出来,
presentViewController(picker, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//初始化,类型为音乐
picker = MPMediaPickerController(mediaTypes: MPMediaType.Music)
picker.allowsPickingMultipleItems = true //可以选择多个音乐,默认单选
picker.delegate = self //委托
player = MPMusicPlayerController.iPodMusicPlayer()//初始化1,即使程序退出也会继续播放
// player = MPMusicPlayerController.applicationMusicPlayer()//初始化2,程序退出,或者后台,音乐就会停止
}
func mediaPicker(mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
// "有选择到一些内容"
//选择后隐藏当前界面即消失
mediaPicker.dismissViewControllerAnimated(true, completion: nil)
player.setQueueWithItemCollection(mediaItemCollection)
player.play() //播放
//获取音乐信息
//获取音乐的名字
let name = mediaItemCollection.items[0].valueForProperty(MPMediaItemPropertyAlbumTitle)
print("name:\(name)")
// print("pick some \(mediaItemCollection)")//选择点击后输出消息
}
func mediaPickerDidCancel(mediaPicker: MPMediaPickerController) {
print("Cancel")
//取消事件
mediaPicker.dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
IOS 播放音乐库的音乐
最新推荐文章于 2024-05-09 09:50:06 发布