Reorganized the Recording package target into folders.

This commit is contained in:
2026-07-04 00:07:42 +02:00
parent fe08548b08
commit aa9ec01611
19 changed files with 103 additions and 112 deletions
-136
View File
@@ -1,136 +0,0 @@
import AVFoundation
import Recording
/// The recording service used by the Attendi sample app, which captures real audio from the device's microphone.
///
/// The service records into a temporary `.m4a` file through an `AVAudioRecorder`, and returns the file's contents when the recording stops.
/// The user's permission to record is requested before a recording starts and, on the platforms that require it, the shared audio session is
/// configured for recording while the capture is in progress.
@MainActor
final class AudioRecordingService: RecordingService {
// MARK: Properties
/// The recorder that captures the audio from the microphone into a temporary file.
private var recorder: AVAudioRecorder?
// MARK: Initializers
/// Creates an audio recording service.
init() {}
// MARK: Methods
/// Starts a new audio recording from the microphone.
///
/// - Throws: ``AudioRecordingError/permissionNotGranted`` when the user denies the app access to the microphone,
/// ``AudioRecordingError/captureNotStarted`` when the recorder fails to start, or any error thrown while configuring
/// the audio session or creating the recorder.
func start() async throws {
guard await AVAudioApplication.requestRecordPermission() else {
throw AudioRecordingError.permissionNotGranted
}
#if os(iOS) || os(visionOS)
let session = AVAudioSession.sharedInstance()
try session.setCategory(.record, mode: .default)
try session.setActive(true)
#endif
let recorder = try AVAudioRecorder(
url: Constant.File.url,
settings: Constant.Audio.settings
)
guard recorder.record() else {
throw AudioRecordingError.captureNotStarted
}
self.recorder = recorder
}
/// Pauses the ongoing recording.
///
/// - Throws: ``AudioRecordingError/noOngoingRecording`` when no recording is in progress.
func pause() async throws {
guard let recorder else {
throw AudioRecordingError.noOngoingRecording
}
recorder.pause()
}
/// Resumes a paused recording.
///
/// - Throws: ``AudioRecordingError/noOngoingRecording`` when no recording is in progress, or
/// ``AudioRecordingError/captureNotStarted`` when the recorder fails to resume.
func resume() async throws {
guard let recorder else {
throw AudioRecordingError.noOngoingRecording
}
guard recorder.record() else {
throw AudioRecordingError.captureNotStarted
}
}
/// Stops the recording, deleting the temporary audio file after its contents are read.
///
/// - Returns: The audio captured since the recording started.
/// - Throws: ``AudioRecordingError/noOngoingRecording`` when no recording is in progress, or any error thrown
/// while reading the recorded audio file.
func stop() async throws -> Data {
guard let recorder else {
throw AudioRecordingError.noOngoingRecording
}
recorder.stop()
self.recorder = nil
#if os(iOS) || os(visionOS)
try? AVAudioSession.sharedInstance().setActive(false)
#endif
defer {
try? FileManager.default.removeItem(at: Constant.File.url)
}
return try Data(contentsOf: Constant.File.url)
}
}
// MARK: - Errors
/// The errors thrown by ``AudioRecordingService``.
enum AudioRecordingError: Error {
/// The recorder failed to start or resume the audio capture.
case captureNotStarted
/// No recording is in progress.
case noOngoingRecording
/// The user denied the app permission to record audio from the microphone.
case permissionNotGranted
}
// MARK: - Constants
/// The constant values used across the audio recording service.
private enum Constant {
/// The audio constants.
enum Audio {
/// The settings of the recorded audio: single-channel AAC at a 44.1 kHz sample rate, encoded in high quality.
static let settings: [String: Any] = [
AVFormatIDKey: kAudioFormatMPEG4AAC,
AVNumberOfChannelsKey: 1,
AVSampleRateKey: 44_100.0,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue,
]
}
/// The file constants.
enum File {
/// The location of the temporary file the audio is captured into.
static let url = FileManager.default.temporaryDirectory.appending(path: "recording.m4a")
}
}
@@ -1,81 +0,0 @@
import AVFoundation
import Recording
import Speech
/// The transcribing service used by the Attendi sample app, which transcribes recorded audio into text on device.
///
/// The service writes the recorded audio into a temporary `.m4a` file and runs it through a `SpeechAnalyzer` with a `SpeechTranscriber`
/// module, joining the finalized results into the returned text. The speech model assets for the current locale are downloaded and installed
/// on first use; every transcription after that happens entirely offline.
struct AudioTranscribingService: TranscribingService {
// MARK: Initializers
/// Creates a speech transcribing service.
init() {}
// MARK: Methods
/// Transcribes the given recorded audio into text, deleting the temporary audio file when the transcription finishes.
///
/// - Parameter audio: The recorded audio to transcribe.
/// - Returns: The transcription of the recorded audio.
/// - Throws: ``AudioTranscribingError/localeNotSupported`` when the transcriber does not support the current locale, or any
/// error thrown while installing the speech model assets, reading the audio file, or analyzing its contents.
func transcribe(_ audio: Data) async throws -> String {
try audio.write(to: Constant.File.url)
defer {
try? FileManager.default.removeItem(at: Constant.File.url)
}
guard let locale = await SpeechTranscriber.supportedLocale(equivalentTo: .current) else {
throw AudioTranscribingError.localeNotSupported
}
let transcriber = SpeechTranscriber(
locale: locale,
preset: .transcription
)
if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) {
try await request.downloadAndInstall()
}
let analyzer = SpeechAnalyzer(modules: [transcriber])
async let text = transcriber.results.reduce(into: "") { text, result in
text += String(result.text.characters)
}
let file = try AVAudioFile(forReading: Constant.File.url)
if let lastSampleTime = try await analyzer.analyzeSequence(from: file) {
try await analyzer.finalizeAndFinish(through: lastSampleTime)
} else {
await analyzer.cancelAndFinishNow()
}
return try await text
}
}
// MARK: - Errors
/// The errors thrown by ``AudioTranscribingService``.
enum AudioTranscribingError: Error {
/// The transcriber does not support the current locale.
case localeNotSupported
}
// MARK: - Constants
/// The constant values used across the speech transcribing service.
private nonisolated enum Constant {
/// The file constants.
enum File {
/// The location of the temporary file the recorded audio is written into for the analysis.
static let url = FileManager.default.temporaryDirectory.appending(path: "transcription.m4a")
}
}