Unc*_*d82 4 audio audio-player artwork ios swift
我想知道是否有一种直接的方式来显示我的音乐播放器正在播放的当前正在播放的MP3文件的图像和标题.我的代码如下,对于这个例子非常简单.我只想使用我在项目中包含的一个.MP3进行测试.
class ViewController: UIViewController {
let audioPath:NSURL! = NSBundle.mainBundle().URLForResource("SippinOnFire", withExtension: "mp3")
@IBOutlet var sliderValue: UISlider!
var player:AVAudioPlayer = AVAudioPlayer()
@IBAction func play(sender: AnyObject) {
player.play()
//println("Playing \(audioPath)")
}
@IBAction func pause(sender: AnyObject) {
player.pause()
}
@IBAction func stop(sender: AnyObject) {
player.stop()
player.currentTime = 0;
}
@IBAction func sliderChanged(sender: AnyObject) {
player.volume = sliderValue.value
}
override func viewDidLoad() {
super.viewDidLoad()
var error:NSError? = nil
player = AVAudioPlayer(contentsOfURL: audioPath!, error: &error)
player.volume = 0.5;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我能够打印到MP3文件的完整路径,但是无法使用显示在项目中显示为我的MP3封面图片的图像,或者只显示播放曲目的标题.有人可以帮我解决这个问题吗?
Leo*_*bus 10
您需要为Media Player添加import语句,并 为nowPlayingInfo属性设置 General Media Item属性键.对于MPMediaItemPropertyArtwork,您需要查看此MPMediaItemArtwork
import MediaPlayer
let audioInfo = MPNowPlayingInfoCenter.defaultCenter()
let audioName = audioPath.lastPathComponent!.stringByDeletingPathExtension
audioInfo.nowPlayingInfo = [ MPMediaItemPropertyTitle: audioName, MPMediaItemPropertyArtist:"artistName"]
Run Code Online (Sandbox Code Playgroud)
要从mp3中提取元数据,您需要创建一个AVPlayerItem并访问其资产commonMetadata属性
let playerItem = AVPlayerItem(URL: audioPath)
let metadataList = playerItem.asset.commonMetadata as! [AVMetadataItem]
for item in metadataList {
if item.commonKey == "title" {
println("Title = " + item.stringValue)
}
if item.commonKey == "artist" {
println("Artist = " + item.stringValue)
}
}
Run Code Online (Sandbox Code Playgroud)
注意:您必须调用beginReceivingRemoteControlEvents(),否则它将无法在实际设备上运行.
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5626 次 |
最近记录: |