当我打开一个视图时,音乐开始使用AVFoundation
播放,然后当它结束时,如何在停止时创建一个动作?因此,当音乐文件结束时,我希望“暂停”按钮变为“播放”。我已经知道如何使用btnPausePlay.setTitle("Pause", forState: UIControlState.Normal)
以编程方式更改文本,但如何在音乐停止播放时创建该功能?
注意:我正在使用swift
答案 0 :(得分:1)
您可以使用委托函数,这是完整的代码:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var player = AVAudioPlayer()
@IBOutlet weak var musicSlider: UISlider!
@IBOutlet weak var btnPausePlay: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
musicSlider.value = 0.0
music()
}
func updateMusicSlider(){
musicSlider.value = Float(player.currentTime)
}
@IBAction func sliderAction(sender: AnyObject) {
player.stop()
player.currentTime = NSTimeInterval(musicSlider.value)
player.play()
}
func music(){
var audioPath = NSBundle.mainBundle().pathForResource("1", ofType: "mp3")!
var error : NSError? = nil
player = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath), error: &error)
musicSlider.maximumValue = Float(player.duration)
var timer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: Selector("updateMusicSlider"), userInfo: nil, repeats: true)
player.delegate = self
if error == nil {
player.delegate = self
player.prepareToPlay()
player.play()
}
}
//This delegate method will call when your player finish playing.
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool)
{
btnPausePlay.setTitle("Play", forState: .Normal)
}
}
HERE是您的示例项目以获取更多信息。