我开始工作了,但当我选择要播放的歌曲时,歌曲的标题并没有第一次出现。我必须回到媒体选择器,再次选择歌曲以显示歌曲的标题。为什么我第一次选择这首歌时它不起作用?另外,当我选择另一首歌播放时,我该如何删除歌曲的标题?非常感谢。这是我的代码:
func mediaPicker(mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
if mediaItemCollection.items.count == 2{
mediaPicker.dismissViewControllerAnimated(true, completion: nil)
let aMediaItem = mediaItemCollection.items[0] as MPMediaItem
music = aMediaItem
NSLog("(aMediaItem.title)selected")
let url: NSURL = (music.valueForProperty(MPMediaItemPropertyAssetURL) as? NSURL)!
do {
musicPlayer = try AVAudioPlayer(contentsOfURL: url)
} catch {
return
}
titleLabel2.text = music.title
titleLabel2 = SKLabelNode(fontNamed: "TimeBurner")
titleLabel2.fontColor = UIColor.whiteColor()
titleLabel2.zPosition = 40
titleLabel2.fontSize = 16
titleLabel2.position = CGPointMake(self.size.width / 5.3, self.size.height / 1.2)
addChild(titleLabel2)
let aMediaItem2 = mediaItemCollection.items[1] as MPMediaItem
music2 = aMediaItem2
NSLog("(aMediaItem2.title)selected")
let url2: NSURL = (music2.valueForProperty(MPMediaItemPropertyAssetURL) as? NSURL)!
do {
musicPlayer2 = try AVAudioPlayer(contentsOfURL: url2)
} catch {
return
}
titleLabel.text = music2.title
titleLabel = SKLabelNode(fontNamed: "TimeBurner")
titleLabel.fontColor = UIColor.whiteColor()
titleLabel.zPosition = 40
titleLabel.fontSize = 16
titleLabel.position = CGPointMake(self.size.width / 1.3, self.size.height / 1.2)
addChild(self.titleLabel)
}
}
下面是我如何让它工作的。我将标题标签添加到didmovetoview中,并将文本添加到didPickMediaItems中。
override func didMoveToView(view: SKView) {
titleLabel2 = SKLabelNode(fontNamed: "TimeBurner")
titleLabel2.fontColor = UIColor.whiteColor()
titleLabel2.zPosition = 40
titleLabel2.fontSize = 16
titleLabel2.position = CGPointMake(self.size.width / 6.0, self.size.height / 1.25)
addChild(titleLabel2)
titleLabel = SKLabelNode(fontNamed: "TimeBurner")
titleLabel.fontColor = UIColor.whiteColor()
titleLabel.zPosition = 40
titleLabel.fontSize = 16
titleLabel.position = CGPointMake(self.size.width / 1.2, self.size.height / 1.25)
addChild(self.titleLabel)
}
func mediaPicker(mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
if mediaItemCollection.items.count == 2{
mediaPicker.dismissViewControllerAnimated(true, completion: nil)
let aMediaItem = mediaItemCollection.items[0] as MPMediaItem
music = aMediaItem
NSLog("(aMediaItem.title)selected")
let url: NSURL = (music.valueForProperty(MPMediaItemPropertyAssetURL) as? NSURL)!
do {
musicPlayer = try AVAudioPlayer(contentsOfURL: url)
} catch {
return
}
titleLabel2.text = music.title
let aMediaItem2 = mediaItemCollection.items[1] as MPMediaItem
music2 = aMediaItem2
NSLog("(aMediaItem2.title)selected")
let url2: NSURL = (music2.valueForProperty(MPMediaItemPropertyAssetURL) as? NSURL)!
do {
musicPlayer2 = try AVAudioPlayer(contentsOfURL: url2)
} catch {
return
}
titleLabel.text = music2.title
addChild(self.titleLabel)
}
}