iOS Swift AVAudioPlayer如何在完成播放时将currentTime重置为零

时间:2016-07-26 20:15:32

标签: ios swift avaudioplayer

我的代码应按下按钮播放C大调波形文件。点击单独的停止按钮将停止播放并将currentTime重置为零。

@IBAction func onPlayButtonClick(sender: UIButton)
{
    play.enabled = false
    let path = NSBundle.mainBundle().pathForResource("cmajor", ofType: "wav")!
    let url = NSURL(fileURLWithPath:  path)
    do
    {
        scalePlayer = try AVAudioPlayer(contentsOfURL: url)
        scalePlayer.prepareToPlay()
        scalePlayer.enableRate = true
        scalePlayer.rate = 0.75
        scalePlayer.play()
    }
    catch
    {

    }

}

它按预期工作,但如何在文件播放完毕后将currentTime设置为零?我无法在开发人员文档中找到任何内容。

1 个答案:

答案 0 :(得分:0)

您必须设置一个代理:

scalePlayer.delegate = self

然后实现此回调

func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
    //set the current time here
    scalePlayer.currentTime = 0
} 

<强>更新

以下是一个如何实现此目的的示例(基于您的代码):

class MyViewController: UIViewController, AVAudioPlayerDelegate {

    @IBOutlet weak var play: UIButton!

    private var scalePlayer: AVAudioPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        let path = NSBundle.mainBundle().pathForResource("cmajor", ofType: "wav")!
        let url = NSURL(fileURLWithPath:  path)
        scalePlayer = try? AVAudioPlayer(contentsOfURL: url)

        scalePlayer?.delegate = self
    }

    @IBAction func onPlayButtonClick(sender: UIButton) {
        play.enabled = false
        scalePlayer?.prepareToPlay()
        scalePlayer?.enableRate = true
        scalePlayer?.rate = 0.75
        scalePlayer?.play()
    }

    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        scalePlayer?.currentTime = 0
    }
}