81 lines
1.9 KiB
Swift
81 lines
1.9 KiB
Swift
//
|
|
// RecordPlayerService.swift
|
|
// AutoCatCore
|
|
//
|
|
// Created by Selim Mustafaev on 31.03.2025.
|
|
// Copyright © 2025 Selim Mustafaev. All rights reserved.
|
|
//
|
|
|
|
import AVFoundation
|
|
|
|
public final class RecordPlayerService: NSObject {
|
|
|
|
var player: AVAudioPlayer?
|
|
var record: AudioRecordDto?
|
|
var onStop: ((AudioRecordDto, Error?) -> Void)?
|
|
}
|
|
|
|
extension RecordPlayerService: RecordPlayerServiceProtocol {
|
|
|
|
public func play(record: AudioRecordDto, onStop: ((AudioRecordDto, Error?) -> Void)?) throws {
|
|
|
|
player?.stop()
|
|
|
|
let url = try FileManager.default.url(for: record.path, in: Constants.audioRecordsFolder)
|
|
player = try AVAudioPlayer(contentsOf: url)
|
|
player?.delegate = self
|
|
|
|
self.record = record
|
|
self.onStop = onStop
|
|
|
|
// try AVAudioSession.sharedInstance().setCategory(.playback)
|
|
// try AVAudioSession.sharedInstance().setActive(true)
|
|
|
|
print("==== playing started ====")
|
|
player?.play()
|
|
}
|
|
|
|
public func pause() {
|
|
|
|
player?.pause()
|
|
}
|
|
|
|
public var currentPlayingId: TimeInterval? {
|
|
guard player?.isPlaying == true else {
|
|
return nil
|
|
}
|
|
|
|
return record?.id
|
|
}
|
|
}
|
|
|
|
extension RecordPlayerService: AVAudioPlayerDelegate {
|
|
|
|
public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
|
|
guard let record else {
|
|
return
|
|
}
|
|
|
|
print("==== playing stopped ====")
|
|
onStop?(record, nil)
|
|
reset()
|
|
}
|
|
|
|
public func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: (any Error)?) {
|
|
guard let record else {
|
|
return
|
|
}
|
|
|
|
print("==== playing error ====")
|
|
onStop?(record, error)
|
|
reset()
|
|
}
|
|
|
|
func reset() {
|
|
|
|
onStop = nil
|
|
player = nil
|
|
record = nil
|
|
}
|
|
}
|