web-dev-qa-db-fra.com

rapide. AVPlayer. Comment suivre quand la chanson a fini de jouer?

Quel est le moyen le plus à l'est de suivre lorsque la chanson a fini de jouer avec AVPlayer dans Swift?

Existe-t-il une fonction appelée lorsque avplayer a terminé de jouer ou dois-je associer un timer avec des références de classe avplayer?

21
Mega4alik

Quelque chose comme ça marche:

func play(url: NSURL) {
    let item = AVPlayerItem(URL: url)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: item)

    let player = AVPlayer(playerItem: item)
    player.play()
}

func playerDidFinishPlaying(note: NSNotification) {
    // Your code here
}

N'oubliez pas de supprimer l'observateur lorsque vous avez terminé (ou dans deinit)!

52
Jernej Strasner

Vous devez créer un objet qui implémente le protocole AVAudioPlayerDelegate et l'utiliser comme délégué de l'objet AVAudioPlayer. Puis reliez-les ensemble, par exemple:

audioPlayer = try! AVAudioPlayer(contentsOf: audioFileUrl)
audioPlayer.delegate = self

Le délégué peut implémenter des méthodes qui répondent à certains événements. Celui-ci se déclenche à la fin de la lecture du son:

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    // ...
}
11
Flimm

Une autre version pour Swift 3

NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)

func playerDidFinishPlaying(sender: Notification) {

    // Do Something
}
7
Mike Carpenter

pour Swift 4.2

func play(url: URL) {
    let item = AVPlayerItem(url: url)
    NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)

    let player = AVPlayer(playerItem: item)
    player.play() 
}

@objc func playerDidFinishPlaying(sender: Notification) {
    // Your code here
}
7
Ajharul Islam

une solution plus complète est ici:

import UIKit
import AVFoundation
import MediaPlayer


class ViewController: UIViewController,AVAudioPlayerDelegate {

    var player: AVAudioPlayer = AVAudioPlayer()

    @IBAction func play(_ sender: UIButton) {
        player.play()
        player.currentTime=14*60-10
        print(player.currentTime)
    }
    @IBAction func pause(_ sender: UIButton) {
        player.pause()
    }
    @IBAction func replay(_ sender: UIButton) {
        player.currentTime=0
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        do{
            let audioPath = Bundle.main.path(forResource: "elon", ofType: "mp3")
            player = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: audioPath!))
            player.prepareToPlay()
            player.delegate = self
        }
        catch{
            print(error)
        }
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool){
        print(flag)
        print("here")
        if flag == true{

        }
    }


}
2
Martian2049

Pour Swif3, vous devrez changer comme suit:

func play(url: NSURL) {
let item = AVPlayerItem(URL: url)
  NotificationCenter.default.addObserver(self,selector:Selector("playerDidFinishPlaying"), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)

let player = AVPlayer(playerItem: item)
player.play() 
}

func playerDidFinishPlaying() {
// Your code here
} 
2
Mohd Ahmed
import AVFoundation

var AVPlayerCustom:AVAudioPlayer = AVAudioPlayer()


class PlayerModule: NSObject, AVAudioPlayerDelegate {

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        print("Finish")
    }

    func playWithData(data: Data, proc: Int) {
        //print(data)

        do {

            AVPlayerCustom = try AVAudioPlayer(data: data)

            AVPlayerCustom.delegate = self as! AVAudioPlayerDelegate

            AVPlayerCustom.prepareToPlay()
            AVPlayerCustom.play()


        }
        catch {
            print("error1")
        }
    }
}
0
Lizzz