Swift:不会调用AudioPlayerDidFinished

时间:2015-11-14 10:33:25

标签: swift avaudioplayer

音频播放完毕后,我的AudioPlayerDidFinishPlaying将不会被调用。我知道这与我的代表有关,但我无法自行解决。

有人可以给我一些提示吗?我用Google搜索了很多,我在这里发现了同样问题的其他问题,但它对我没有用。

由于

import UIKit
import Parse
import AVFoundation

class ViewControllerMies: UIViewController, AVAudioPlayerDelegate {

var timer = NSTimer()
var player: AVAudioPlayer = AVAudioPlayer()
var currentStateAudio = ""
var oldAudio = String()

func startTimer() {

    if player.playing == false {
        print("Tijd voor de Spice Girls")
    }

    let query = PFQuery(className:"CurrentState")
    query.getObjectInBackgroundWithId("9r61TRaRqu") {
        (objects: PFObject?, error: NSError?) -> Void in
        if error == nil && objects != nil {

            self.currentStateAudio = objects!.objectForKey("currentState") as! String
            print(self.currentStateAudio)

        } else {
            print(error)
        }
    }

    if (oldAudio != self.currentStateAudio)
    {

        let audioPath = NSBundle.mainBundle().pathForResource(self.currentStateAudio, ofType: "mp3")!

        do {

            try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))


        } catch {

            // Process error here

        }

        player.play()

        oldAudio = self.currentStateAudio

    }

}

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("startTimer"), userInfo: nil, repeats: true)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool)
{
    print("Finished Playing")

}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

2 个答案:

答案 0 :(得分:6)

您并未将自己设定为玩家的代表

在致电play()之前执行player.delegate = self

答案 1 :(得分:2)

如果您使用的是私人委托,则它不会调用它来解决此问题

//MARK:- This is correct delegate working fine (use this)
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    audioRecorder = nil
}
//MARK:- Insted of this (this will not call)
private func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    audioRecorder = nil
}