session-ios/Session/Components/VoiceMessageView.swift

215 lines
9.1 KiB
Swift
Raw Normal View History

2020-09-30 06:39:56 +02:00
import Accelerate
import NVActivityIndicatorView
2020-09-30 06:39:56 +02:00
2020-10-02 03:24:36 +02:00
@objc(LKVoiceMessageView)
final class VoiceMessageView : UIView {
2020-10-01 01:25:17 +02:00
private let voiceMessage: TSAttachment
2020-10-02 03:04:37 +02:00
private let isOutgoing: Bool
2020-10-05 01:51:26 +02:00
private var isLoading = false
2020-10-05 01:54:27 +02:00
private var isForcedAnimation = false
2020-10-01 01:25:17 +02:00
private var volumeSamples: [Float] = [] { didSet { updateShapeLayers() } }
2020-10-05 01:51:26 +02:00
@objc var progress: CGFloat = 0 { didSet { updateShapeLayers() } }
2020-10-01 10:15:48 +02:00
@objc var duration: Int = 0 { didSet { updateDurationLabel() } }
2020-10-02 06:44:33 +02:00
@objc var isPlaying = false { didSet { updateToggleImageView() } }
2020-09-30 06:39:56 +02:00
// MARK: Components
2020-10-02 06:44:33 +02:00
private lazy var toggleImageView = UIImageView(image: #imageLiteral(resourceName: "Play"))
private lazy var spinner = NVActivityIndicatorView(frame: CGRect.zero, type: .circleStrokeSpin, color: .black, padding: nil)
2020-10-01 10:15:48 +02:00
private lazy var durationLabel: UILabel = {
let result = UILabel()
result.textColor = Colors.text
result.font = .systemFont(ofSize: Values.mediumFontSize)
return result
}()
2020-09-30 06:39:56 +02:00
private lazy var backgroundShapeLayer: CAShapeLayer = {
let result = CAShapeLayer()
result.fillColor = Colors.text.cgColor
return result
}()
private lazy var foregroundShapeLayer: CAShapeLayer = {
let result = CAShapeLayer()
2020-10-02 03:04:37 +02:00
result.fillColor = (isLightMode && isOutgoing) ? UIColor.white.cgColor : Colors.accent.cgColor
2020-09-30 06:39:56 +02:00
return result
}()
// MARK: Settings
2020-10-05 01:51:26 +02:00
private let leadingInset: CGFloat = 0
2020-09-30 06:39:56 +02:00
private let sampleSpacing: CGFloat = 1
2020-10-05 01:51:26 +02:00
private let targetSampleCount = 48
2020-10-02 06:44:33 +02:00
private let toggleContainerSize: CGFloat = 32
2020-10-05 01:51:26 +02:00
private let vMargin: CGFloat = 0
2020-09-30 06:39:56 +02:00
2020-10-02 06:44:33 +02:00
@objc public static let contentHeight: CGFloat = 40
2020-10-01 06:24:00 +02:00
2020-09-30 06:39:56 +02:00
// MARK: Initialization
2020-10-02 03:04:37 +02:00
@objc(initWithVoiceMessage:isOutgoing:)
init(voiceMessage: TSAttachment, isOutgoing: Bool) {
2020-10-01 01:25:17 +02:00
self.voiceMessage = voiceMessage
2020-10-02 03:04:37 +02:00
self.isOutgoing = isOutgoing
2020-09-30 06:39:56 +02:00
super.init(frame: CGRect.zero)
}
override init(frame: CGRect) {
2020-10-01 01:25:17 +02:00
preconditionFailure("Use init(voiceMessage:associatedWith:) instead.")
2020-09-30 06:39:56 +02:00
}
required init?(coder: NSCoder) {
2020-10-01 01:25:17 +02:00
preconditionFailure("Use init(voiceMessage:associatedWith:) instead.")
2020-09-30 06:39:56 +02:00
}
2020-10-02 04:09:38 +02:00
@objc func initialize() {
2020-09-30 06:39:56 +02:00
setUpViewHierarchy()
2020-10-01 01:25:17 +02:00
if voiceMessage.isDownloaded {
guard let url = (voiceMessage as? TSAttachmentStream)?.originalMediaURL else {
return print("[Loki] Couldn't get URL for voice message.")
}
2020-10-01 10:15:48 +02:00
if let cachedVolumeSamples = Storage.getVolumeSamples(for: voiceMessage.uniqueId!), cachedVolumeSamples.count == targetSampleCount {
2020-10-05 01:51:26 +02:00
self.hideLoader()
2020-10-01 06:24:00 +02:00
self.volumeSamples = cachedVolumeSamples
} else {
let voiceMessageID = voiceMessage.uniqueId!
2020-10-01 10:15:48 +02:00
AudioUtilities.getVolumeSamples(for: url, targetSampleCount: targetSampleCount).done(on: DispatchQueue.main) { [weak self] volumeSamples in
2020-10-01 06:24:00 +02:00
guard let self = self else { return }
2020-10-05 01:51:26 +02:00
self.hideLoader()
2020-10-05 01:54:27 +02:00
self.isForcedAnimation = true
2020-10-01 06:24:00 +02:00
self.volumeSamples = volumeSamples
Storage.write { transaction in
Storage.setVolumeSamples(for: voiceMessageID, to: volumeSamples, using: transaction)
}
}.catch(on: DispatchQueue.main) { error in
print("[Loki] Couldn't sample audio file due to error: \(error).")
}
2020-10-01 01:25:17 +02:00
}
} else {
2020-10-05 01:51:26 +02:00
showLoader()
2020-09-30 06:39:56 +02:00
}
}
private func setUpViewHierarchy() {
set(.width, to: 200)
2020-10-02 03:24:36 +02:00
set(.height, to: VoiceMessageView.contentHeight)
2020-09-30 06:39:56 +02:00
layer.insertSublayer(backgroundShapeLayer, at: 0)
layer.insertSublayer(foregroundShapeLayer, at: 1)
2020-10-02 06:44:33 +02:00
let toggleContainer = UIView()
toggleContainer.clipsToBounds = false
toggleContainer.addSubview(toggleImageView)
toggleImageView.set(.width, to: 12)
toggleImageView.set(.height, to: 12)
toggleImageView.center(in: toggleContainer)
toggleContainer.addSubview(spinner)
spinner.set(.width, to: 24)
spinner.set(.height, to: 24)
spinner.center(in: toggleContainer)
2020-10-02 06:44:33 +02:00
toggleContainer.set(.width, to: toggleContainerSize)
toggleContainer.set(.height, to: toggleContainerSize)
toggleContainer.layer.cornerRadius = toggleContainerSize / 2
toggleContainer.backgroundColor = UIColor.white
let glowRadius: CGFloat = isLightMode ? 1 : 2
let glowColor = isLightMode ? UIColor.black.withAlphaComponent(0.4) : UIColor.black
let glowConfiguration = UIView.CircularGlowConfiguration(size: toggleContainerSize, color: glowColor, radius: glowRadius)
toggleContainer.setCircularGlow(with: glowConfiguration)
addSubview(toggleContainer)
toggleContainer.center(.vertical, in: self)
toggleContainer.pin(.leading, to: .leading, of: self, withInset: leadingInset)
2020-10-01 10:15:48 +02:00
addSubview(durationLabel)
durationLabel.center(.vertical, in: self)
durationLabel.pin(.trailing, to: .trailing, of: self)
2020-09-30 06:39:56 +02:00
}
2020-10-01 01:25:17 +02:00
// MARK: UI & Updating
2020-10-05 01:51:26 +02:00
private func showLoader() {
isLoading = true
toggleImageView.isHidden = true
spinner.startAnimating()
spinner.isHidden = false
2020-10-05 01:51:26 +02:00
Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak self] timer in
guard let self = self else { return timer.invalidate() }
if self.isLoading {
self.updateFakeVolumeSamples()
} else {
timer.invalidate()
}
}
updateFakeVolumeSamples()
}
private func updateFakeVolumeSamples() {
let fakeVolumeSamples = (0..<targetSampleCount).map { _ in Float.random(in: 0...1) }
volumeSamples = fakeVolumeSamples
}
private func hideLoader() {
isLoading = false
toggleImageView.isHidden = false
spinner.stopAnimating()
spinner.isHidden = true
2020-10-01 01:25:17 +02:00
}
2020-10-05 01:51:26 +02:00
override func layoutSubviews() {
super.layoutSubviews()
2020-10-01 01:25:17 +02:00
updateShapeLayers()
2020-09-30 06:39:56 +02:00
}
2020-10-01 01:25:17 +02:00
private func updateShapeLayers() {
2020-10-02 06:44:33 +02:00
clipsToBounds = false // Bit of a hack to do this here, but the containing stack view turns this off all the time
2020-09-30 06:39:56 +02:00
guard !volumeSamples.isEmpty else { return }
2020-10-01 10:15:48 +02:00
let sMin = CGFloat(volumeSamples.min()!)
let sMax = CGFloat(volumeSamples.max()!)
2020-10-02 06:44:33 +02:00
let w = width() - leadingInset - toggleContainerSize - durationLabel.width() - 2 * Values.smallSpacing
2020-10-01 10:15:48 +02:00
let h = height() - 2 * vMargin
let sW = (w - sampleSpacing * CGFloat(volumeSamples.count - 1)) / CGFloat(volumeSamples.count)
2020-09-30 06:39:56 +02:00
let backgroundPath = UIBezierPath()
let foregroundPath = UIBezierPath()
for (i, value) in volumeSamples.enumerated() {
2020-10-02 06:44:33 +02:00
let x = leadingInset + toggleContainerSize + Values.smallSpacing + CGFloat(i) * (sW + sampleSpacing)
2020-10-01 10:15:48 +02:00
let fraction = (CGFloat(value) - sMin) / (sMax - sMin)
let sH = max(8, h * fraction)
let y = vMargin + (h - sH) / 2
2020-09-30 06:39:56 +02:00
let subPath = UIBezierPath(roundedRect: CGRect(x: x, y: y, width: sW, height: sH), cornerRadius: sW / 2)
backgroundPath.append(subPath)
2020-10-01 06:24:00 +02:00
if progress > CGFloat(i) / CGFloat(volumeSamples.count) { foregroundPath.append(subPath) }
2020-09-30 06:39:56 +02:00
}
backgroundPath.close()
foregroundPath.close()
2020-10-05 01:54:27 +02:00
if isLoading || isForcedAnimation {
2020-10-05 01:51:26 +02:00
let animation = CABasicAnimation(keyPath: "path")
animation.duration = 0.25
animation.toValue = backgroundPath
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
backgroundShapeLayer.add(animation, forKey: "path")
backgroundShapeLayer.path = backgroundPath.cgPath
} else {
backgroundShapeLayer.path = backgroundPath.cgPath
}
2020-09-30 06:39:56 +02:00
foregroundShapeLayer.path = foregroundPath.cgPath
2020-10-05 01:54:27 +02:00
isForcedAnimation = false
2020-09-30 06:39:56 +02:00
}
2020-10-01 10:15:48 +02:00
private func updateDurationLabel() {
durationLabel.text = OWSFormat.formatDurationSeconds(duration)
updateShapeLayers()
}
2020-10-02 06:44:33 +02:00
private func updateToggleImageView() {
toggleImageView.image = isPlaying ? #imageLiteral(resourceName: "Pause") : #imageLiteral(resourceName: "Play")
}
2020-10-19 02:21:04 +02:00
// MARK: Interaction
@objc(getCurrentTime:)
func getCurrentTime(for panGestureRecognizer: UIPanGestureRecognizer) -> TimeInterval {
guard voiceMessage.isDownloaded else { return 0 }
let locationInSelf = panGestureRecognizer.location(in: self)
let waveformFrameOrigin = CGPoint(x: leadingInset + toggleContainerSize + Values.smallSpacing, y: vMargin)
let waveformFrameSize = CGSize(width: width() - leadingInset - toggleContainerSize - durationLabel.width() - 2 * Values.smallSpacing,
height: height() - 2 * vMargin)
let waveformFrame = CGRect(origin: waveformFrameOrigin, size: waveformFrameSize)
guard waveformFrame.contains(locationInSelf) else { return 0 }
let fraction = (locationInSelf.x - waveformFrame.minX) / (waveformFrame.maxX - waveformFrame.minX)
return Double(fraction) * Double(duration)
}
2020-09-30 06:39:56 +02:00
}