2018-02-03 00:35:32 +01:00
|
|
|
//
|
|
|
|
// Copyright (c) 2018 Open Whisper Systems. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import AVFoundation
|
|
|
|
|
|
|
|
@objc
|
|
|
|
protocol OWSVideoPlayerDelegate: class {
|
|
|
|
func videoPlayerDidPlayToCompletion(_ videoPlayer: OWSVideoPlayer)
|
|
|
|
}
|
|
|
|
|
|
|
|
@objc
|
|
|
|
public class OWSVideoPlayer: NSObject {
|
|
|
|
|
|
|
|
let avPlayer: AVPlayer
|
2018-02-16 21:32:29 +01:00
|
|
|
let audioActivity: AudioActivity
|
2018-02-03 00:35:32 +01:00
|
|
|
|
|
|
|
weak var delegate: OWSVideoPlayerDelegate?
|
|
|
|
|
|
|
|
init(url: URL) {
|
|
|
|
self.avPlayer = AVPlayer(url: url)
|
2018-02-23 18:46:04 +01:00
|
|
|
self.audioActivity = AudioActivity(audioDescription: "[OWSVideoPlayer] url:\(url)")
|
2018-02-03 00:35:32 +01:00
|
|
|
|
|
|
|
super.init()
|
|
|
|
|
|
|
|
NotificationCenter.default.addObserver(self,
|
|
|
|
selector: #selector(playerItemDidPlayToCompletion(_:)),
|
|
|
|
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
|
|
|
|
object: avPlayer.currentItem)
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Playback Controls
|
|
|
|
|
|
|
|
public func pause() {
|
|
|
|
avPlayer.pause()
|
2018-02-16 21:32:29 +01:00
|
|
|
OWSAudioSession.shared.endAudioActivity(self.audioActivity)
|
2018-02-03 00:35:32 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
public func play() {
|
2018-03-05 23:59:09 +01:00
|
|
|
OWSAudioSession.shared.startPlaybackAudioActivity(self.audioActivity)
|
2018-02-03 00:35:32 +01:00
|
|
|
|
|
|
|
guard let item = avPlayer.currentItem else {
|
|
|
|
owsFail("\(logTag) video player item was unexpectedly nil")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if item.currentTime() == item.duration {
|
|
|
|
// Rewind for repeated plays, but only if it previously played to end.
|
|
|
|
avPlayer.seek(to: kCMTimeZero)
|
|
|
|
}
|
|
|
|
|
|
|
|
avPlayer.play()
|
|
|
|
}
|
|
|
|
|
|
|
|
@objc(seekToTime:)
|
|
|
|
public func seek(to time: CMTime) {
|
|
|
|
avPlayer.seek(to: time)
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: private
|
|
|
|
|
|
|
|
@objc
|
|
|
|
private func playerItemDidPlayToCompletion(_ notification: Notification) {
|
|
|
|
self.delegate?.videoPlayerDidPlayToCompletion(self)
|
2018-02-16 21:32:29 +01:00
|
|
|
OWSAudioSession.shared.endAudioActivity(self.audioActivity)
|
2018-02-03 00:35:32 +01:00
|
|
|
}
|
|
|
|
}
|