(iOS) 音乐文件停止时的动作
(iOS) Action when music file stops
当我打开一个视图时,音乐开始使用 AVFoundation
播放,然后当它结束时,如何在它停止时创建一个动作?所以当音乐文件完成时,我希望 "Pause" 按钮变成 "Play"。我已经知道如何使用 btnPausePlay.setTitle("Pause", forState: UIControlState.Normal)
以编程方式更改文本,但是当音乐停止播放时如何创建函数?
注意:我正在使用 swift
您可以为此使用委托函数,这是您的完整代码:
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 是您的示例项目以获取更多信息。
当我打开一个视图时,音乐开始使用 AVFoundation
播放,然后当它结束时,如何在它停止时创建一个动作?所以当音乐文件完成时,我希望 "Pause" 按钮变成 "Play"。我已经知道如何使用 btnPausePlay.setTitle("Pause", forState: UIControlState.Normal)
以编程方式更改文本,但是当音乐停止播放时如何创建函数?
注意:我正在使用 swift
您可以为此使用委托函数,这是您的完整代码:
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 是您的示例项目以获取更多信息。