AVPlayer 비디오 재생이 종료되는 시점을 탐지하는 방법은 무엇입니까?
저는 스위프트에서 로컬 비디오 파일(mp4)을 재생하기 위해 AVPlayer를 사용하고 있습니다.비디오 재생이 끝나면 감지하는 방법을 아는 사람이 있습니까?감사해요.
다음 정보를AVPlayerItemDidPlayToEndTimeNotification
당신의 목적은 다음과 같아야 합니다. AVPlayerItem
.
이를 위해서는 당신의 속성을 사용하세요.AVPlayer
이제 비디오가 끝나면 알림이 표시됩니다!
내 예를 참조하십시오.
let videoPlayer = AVPlayer(URL: url)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:",
name: AVPlayerItemDidPlayToEndTimeNotification, object: videoPlayer.currentItem)
func playerDidFinishPlaying(note: NSNotification) {
print("Video Finished")
}
스위프트 3
let videoPlayer = AVPlayer(URL: url)
NotificationCenter.default.addObserver(self, selector: Selector(("playerDidFinishPlaying:")),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: videoPlayer.currentItem)
func playerDidFinishPlaying(note: NSNotification) {
print("Video Finished")
}
사용자의 옵저버를 제거하는 것을 잊지 마십시오.deinit
스위프트 4, 5
NotificationCenter.default
.addObserver(self,
selector: #selector(playerDidFinishPlaying),
name: .AVPlayerItemDidPlayToEndTime,
object: videoPlayer.currentItem
)
스위프트 3.0
let videoPlayer = AVPlayer(URL: url)
NotificationCenter.default.addObserver(self, selector:#selector(self.playerDidFinishPlaying(note:)),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
@objc func playerDidFinishPlaying(note: NSNotification){
print("Video Finished")
}
Swift 4.2 버전:
var player: AVPlayer!
//
//
// Configure Player
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let filepath: String? = Bundle.main.path(forResource: "selectedFileName", ofType: "mp4")
if let filepath = filepath {
let fileURL = URL.init(fileURLWithPath: filepath)
player = AVPlayer(url: fileURL)
let playerLayer = AVPlayerLayer(player: player)
// Register for notification
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: nil) // Add observer
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
}
}
// Notification Handling
@objc func playerItemDidReachEnd(notification: NSNotification) {
player.seek(to: CMTime.zero)
player.play()
}
// Remove Observer
deinit {
NotificationCenter.default.removeObserver(self)
}
결합을 사용하려는 경우:
private var cancelBag: Set<AnyCancellable> = []
NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime)
.sink { _ in
player.seek(to: CMTime.zero)
player.play()
}
.store(in: &cancelBag)
SWIFT 3.0의 경우 정상 작동합니다.
class PlayVideoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayVideoViewController.finishVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTimeNotification, object: nil)
}
func finishVideo()
{
print("Video Finished")
}
}
스위프트 4.0
이것은 나에게 효과가 있습니다.@Channel 덕분에
private func playVideo(fileURL: String) {
// Create RUL object
let url = URL(string: fileURL)
// Create Player Item object
let playerItem: AVPlayerItem = AVPlayerItem(url: url!)
// Assign Item to Player
let player = AVPlayer(playerItem: playerItem)
// Prepare AVPlayerViewController
let videoPlayer = AVPlayerViewController()
// Assign Video to AVPlayerViewController
videoPlayer.player = player
NotificationCenter.default.addObserver(self, selector: #selector(myViewController.finishVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
// Present the AVPlayerViewController
present(videoPlayer, animated: true, completion: {
// Play the Video
player.play()
})
}
@objc func finishVideo()
{
print("Video Finished")
}
2019
정말 이렇게 간단합니다.
NotificationCenter.default.addObserver(
self,
selector: #selector(fileComplete),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: nil
)
(객체가 0인 것은 괜찮습니다.)
그리고 나서.
@objc func fileComplete() {
print("IT'S DONE!")
}
SWIFT 5 업데이트
@objc 함수가 있는 관찰자 방법이 네이티브가 아닙니다.swift 5에서 이벤트 퍼블리셔를 사용하는 것이 좋습니다.아주 간단합니다.
구조에서 다음을 선언합니다.
var pub = NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime)
그런 다음 임의의 보기에서 추가
.onReceive(pub) { (output) in
print("Video Finished")
}
스위프트 3.0
let videoPlayer = AVPlayer(URL: url)
NotificationCenter.default.addObserver(self, selector:#selector(self.playerDidFinishPlaying(note:)),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
func playerDidFinishPlaying(note: NSNotification){
//Called when player finished playing
}
SWIFT 3.0의 경우
여기서 'fullUrl'은 동영상의 URL이며 URL에 공백이 없어야 합니다. URL이 작동하도록 'Space'를 '%20'으로 대체해야 합니다.
let videoURL = NSURL(string: fullUrl)
let player = AVPlayer(url: videoURL! as URL)
playerViewController.delegate = self
playerViewController.player = player
self.present(playerViewController, animated: false) {
self.playerViewController.player!.play()
NotificationCenter.default.addObserver(self, selector: #selector(yourViewControllerName.playerDidFinishPlaying), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
}
아래 지정된 방법을 보기 컨트롤러에 추가합니다.
func playerDidFinishPlaying(){
print("Video Finished playing in style")
}
여기에 많은 승인된 답변이 있다는 것을 알고 있습니다.
그러나 다른 경로는 경계 시간 관찰자를 AVP Player에 추가하는 것일 수 있습니다.당신은 비디오의 지속 시간을 가져야 할 것이고, 당신은 그것을 당신의 것으로부터 얻을 수 있습니다.player.currentItem
원하는 시간 경계로 추가합니다.
fileprivate var videoEndObserver: Any?
func addVideoEndObserver() {
guard let player = YOUR_VIDEO_PLAYER else { return }
// This is just in case you are loading a video from a URL.
guard let duration = player.currentItem?.duration, duration.value != 0 else {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { [weak self] in
self?.addVideoEndObserver()
})
return
}
let endTime = NSValue(time: duration - CMTimeMakeWithSeconds(0.1, duration.timescale))
videoEndObserver = player.addBoundaryTimeObserver(forTimes: [endTime], queue: .main, using: {
self.removeVideoEndObserver()
// DO YOUR STUFF HERE...
})
}
func removeVideoEndObserver() {
guard let observer = videoEndObserver else { return }
videoPlayer.player?.removeTimeObserver(observer)
videoEndObserver = nil
}
func shareEditedVedio() -> AVPlayer {
let editedVedioPlayer = AVPlayer(url: self.vedioData.vedioURLWithAddedSounds!)
NotificationCenter.default.addObserver(self, selector:#selector(self.playerDidFinishPlaying(note:)),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: editedVedioPlayer.currentItem)
return editedVedioPlayer
}
@objc func playerDidFinishPlaying(note: NSNotification){
//Called when player finished playing
}
Swift 3 및 RxSwift 3.5에서는 다음 작업만 수행하면 됩니다.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.rx.notification(Notification.Name.AVPlayerItemDidPlayToEndTime)
.asObservable().subscribe(onNext: { [weak self] notification in
//Your action
}).addDisposableTo(disposeBag)
}
사용.Combine
또한 알림이 관심 있는 AVPlayerItem에서 전송되는지 확인합니다.여러 항목을 동시에 재생하기 때문에 그 경우에도 작동합니다.
private var subscriptions: Set<AnyCancellable> = []
NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
.receive(on: RunLoop.main)
.sink { [weak self] notification in
guard let item = notification.object as? AVPlayerItem else { return }
if item == self?.player.currentItem {
//.... Here you know it was the item you are interested in that played to end and not just any
}
}
.store(in: &subscriptions)
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: .main) { noti in
guard let item = noti.object as? AVPlayerItem else{
return
}
//DidPlayToEndTime
}
알림이 호출되지 않는 문제가 발생하여 AVPlayerViewController의 프레젠테이션 내에서 알림을 설정하여 해결했습니다.
func presentVideo(url:URL) {
let player = AVPlayer(url: url)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
DispatchQueue.main.async {
playerViewController.player!.play()
//NOTE: The notification must be created here for it to work as expected
NotificationCenter.default.addObserver(self, selector: #selector(self.videoDidEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}
}
}
다른 솔루션:
player.observe(\AVPlayer.actionAtItemEnd) { player, _ in
print("video did end")
}
언급URL : https://stackoverflow.com/questions/29386531/how-to-detect-when-avplayer-video-ends-playing
'itsource' 카테고리의 다른 글
Windows 10에서 'rimraf는 인식되는 명령이 아닙니다'를 수정하는 방법 (0) | 2023.08.30 |
---|---|
계층형 MariaDB/MySQL 재귀 쿼리(부모 전용) (0) | 2023.08.30 |
UIView에서 선 그리기 (0) | 2023.08.30 |
오라클 테이블에 데이터를 삽입하는 가장 빠른 방법은 무엇입니까? (0) | 2023.08.30 |
ASP를 교체합니다.넷의 세션 전체 (0) | 2023.08.30 |