mirror of
https://github.com/Novaloop-AG/element-x-ios.git
synced 2026-11-04 19:44:05 +00:00
Allow to record a voice message (#1926)
This commit is contained in:
@@ -17,16 +17,14 @@
|
||||
import AVFoundation
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
enum AudioRecorderError: Error {
|
||||
case genericError
|
||||
}
|
||||
import UIKit
|
||||
|
||||
class AudioRecorder: NSObject, AudioRecorderProtocol, AVAudioRecorderDelegate {
|
||||
private let silenceThreshold: Float = -50.0
|
||||
|
||||
private var audioRecorder: AVAudioRecorder?
|
||||
|
||||
private var cancellables = Set<AnyCancellable>()
|
||||
private let actionsSubject: PassthroughSubject<AudioRecorderAction, Never> = .init()
|
||||
var actions: AnyPublisher<AudioRecorderAction, Never> {
|
||||
actionsSubject.eraseToAnyPublisher()
|
||||
@@ -44,7 +42,11 @@ class AudioRecorder: NSObject, AudioRecorderProtocol, AVAudioRecorderDelegate {
|
||||
audioRecorder?.isRecording ?? false
|
||||
}
|
||||
|
||||
func recordWithOutputURL(_ url: URL) {
|
||||
func record(with recordID: AudioRecordingIdentifier) async -> Result<Void, AudioRecorderError> {
|
||||
guard await requestRecordPermission() else {
|
||||
return .failure(.recordPermissionNotGranted)
|
||||
}
|
||||
|
||||
let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
|
||||
AVSampleRateKey: 48000,
|
||||
AVEncoderBitRateKey: 128_000,
|
||||
@@ -54,6 +56,7 @@ class AudioRecorder: NSObject, AudioRecorderProtocol, AVAudioRecorderDelegate {
|
||||
do {
|
||||
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default)
|
||||
try AVAudioSession.sharedInstance().setActive(true)
|
||||
let url = URL.temporaryDirectory.appendingPathComponent("voice-message-\(recordID.identifier).m4a")
|
||||
audioRecorder = try AVAudioRecorder(url: url, settings: settings)
|
||||
audioRecorder?.delegate = self
|
||||
audioRecorder?.isMeteringEnabled = true
|
||||
@@ -63,25 +66,26 @@ class AudioRecorder: NSObject, AudioRecorderProtocol, AVAudioRecorderDelegate {
|
||||
MXLog.error("audio recording failed: \(error)")
|
||||
actionsSubject.send(.didFailWithError(error: error))
|
||||
}
|
||||
}
|
||||
|
||||
func stopRecording() {
|
||||
audioRecorder?.stop()
|
||||
|
||||
do {
|
||||
try AVAudioSession.sharedInstance().setActive(false)
|
||||
} catch {
|
||||
actionsSubject.send(.didFailWithError(error: error))
|
||||
}
|
||||
return .success(())
|
||||
}
|
||||
|
||||
func stopRecording() async {
|
||||
guard let audioRecorder, audioRecorder.isRecording else {
|
||||
return
|
||||
}
|
||||
audioRecorder.stop()
|
||||
}
|
||||
|
||||
func deleteRecording() {
|
||||
audioRecorder?.deleteRecording()
|
||||
}
|
||||
|
||||
func peakPowerForChannelNumber(_ channelNumber: Int) -> Float {
|
||||
guard isRecording, let audioRecorder else {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
audioRecorder.updateMeters()
|
||||
|
||||
return normalizedPowerLevelFromDecibels(audioRecorder.peakPower(forChannel: channelNumber))
|
||||
}
|
||||
|
||||
@@ -91,13 +95,37 @@ class AudioRecorder: NSObject, AudioRecorderProtocol, AVAudioRecorderDelegate {
|
||||
}
|
||||
|
||||
audioRecorder.updateMeters()
|
||||
|
||||
return normalizedPowerLevelFromDecibels(audioRecorder.averagePower(forChannel: channelNumber))
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private func addObservers() {
|
||||
// Stop recording uppon UIApplication.didEnterBackgroundNotification notification
|
||||
NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification)
|
||||
.sink { [weak self] _ in
|
||||
guard let self else { return }
|
||||
Task { await self.stopRecording() }
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
}
|
||||
|
||||
private func removeObservers() {
|
||||
cancellables.removeAll()
|
||||
}
|
||||
|
||||
private func requestRecordPermission() async -> Bool {
|
||||
await withCheckedContinuation { continuation in
|
||||
AVAudioSession.sharedInstance().requestRecordPermission { granted in
|
||||
continuation.resume(returning: granted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AVAudioRecorderDelegate
|
||||
|
||||
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully success: Bool) {
|
||||
try? AVAudioSession.sharedInstance().setActive(false)
|
||||
if success {
|
||||
actionsSubject.send(.didStopRecording)
|
||||
} else {
|
||||
@@ -106,6 +134,7 @@ class AudioRecorder: NSObject, AudioRecorderProtocol, AVAudioRecorderDelegate {
|
||||
}
|
||||
|
||||
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
|
||||
try? AVAudioSession.sharedInstance().setActive(false)
|
||||
actionsSubject.send(.didFailWithError(error: error ?? AudioRecorderError.genericError))
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,24 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
enum AudioRecordingIdentifier {
|
||||
case uuid(UUID)
|
||||
}
|
||||
|
||||
extension AudioRecordingIdentifier {
|
||||
var identifier: String {
|
||||
switch self {
|
||||
case .uuid(let uuid):
|
||||
return uuid.uuidString
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum AudioRecorderError: Error {
|
||||
case genericError
|
||||
case recordPermissionNotGranted
|
||||
}
|
||||
|
||||
enum AudioRecorderAction {
|
||||
case didStartRecording
|
||||
case didStopRecording
|
||||
@@ -29,8 +47,9 @@ protocol AudioRecorderProtocol: AnyObject {
|
||||
var isRecording: Bool { get }
|
||||
var url: URL? { get }
|
||||
|
||||
func recordWithOutputURL(_ url: URL)
|
||||
func stopRecording()
|
||||
func record(with recordID: AudioRecordingIdentifier) async -> Result<Void, AudioRecorderError>
|
||||
func stopRecording() async
|
||||
func deleteRecording()
|
||||
func averagePowerForChannelNumber(_ channelNumber: Int) -> Float
|
||||
}
|
||||
|
||||
|
||||
@@ -30,25 +30,27 @@ class AudioRecorderState: ObservableObject, Identifiable {
|
||||
|
||||
@Published private(set) var recordingState: AudioRecorderRecordingState = .stopped
|
||||
@Published private(set) var duration = 0.0
|
||||
@Published private(set) var waveform = EstimatedWaveform(data: Array(repeating: 0, count: 100))
|
||||
@Published private(set) var waveformSamples: [Float] = []
|
||||
|
||||
private weak var audioRecorder: AudioRecorderProtocol?
|
||||
private var cancellables: Set<AnyCancellable> = []
|
||||
private var displayLink: CADisplayLink?
|
||||
|
||||
func attachAudioRecorder(_ audioRecorder: AudioRecorderProtocol) {
|
||||
if self.audioRecorder != nil {
|
||||
detachAudioRecorder()
|
||||
}
|
||||
recordingState = .stopped
|
||||
self.audioRecorder = audioRecorder
|
||||
subscribeToAudioRecorder(audioRecorder)
|
||||
if audioRecorder.isRecording {
|
||||
startPublishUpdates()
|
||||
}
|
||||
}
|
||||
|
||||
func detachAudioRecorder() {
|
||||
guard audioRecorder != nil else { return }
|
||||
audioRecorder?.stopRecording()
|
||||
func detachAudioRecorder() async {
|
||||
if let audioRecorder, audioRecorder.isRecording {
|
||||
await audioRecorder.stopRecording()
|
||||
}
|
||||
stopPublishUpdates()
|
||||
waveformSamples = []
|
||||
cancellables = []
|
||||
audioRecorder = nil
|
||||
recordingState = .stopped
|
||||
@@ -91,7 +93,7 @@ class AudioRecorderState: ObservableObject, Identifiable {
|
||||
stopPublishUpdates()
|
||||
}
|
||||
displayLink = CADisplayLink(target: self, selector: #selector(publishUpdate))
|
||||
displayLink?.preferredFrameRateRange = .init(minimum: 10, maximum: 20)
|
||||
displayLink?.preferredFrameRateRange = .init(minimum: 30, maximum: 60)
|
||||
displayLink?.add(to: .current, forMode: .common)
|
||||
}
|
||||
|
||||
@@ -99,6 +101,9 @@ class AudioRecorderState: ObservableObject, Identifiable {
|
||||
if let currentTime = audioRecorder?.currentTime {
|
||||
duration = currentTime
|
||||
}
|
||||
if let sample = audioRecorder?.averagePowerForChannelNumber(0) {
|
||||
waveformSamples.append(sample)
|
||||
}
|
||||
}
|
||||
|
||||
private func stopPublishUpdates() {
|
||||
|
||||
Reference in New Issue
Block a user