Record voice in the background SwiftUI

2023-09-18
#swiftui #SwiftUI 学习笔记

Currently, I am working on VoiceBox, which is an application based on Whisper that can transcribe audio offline. To enable this, I needed to build an app that can record audio in the background. After searching online and some trial and error, I was able to get it working. Here are the key steps I took to enable background audio recording in my app

Info.plist

image

add Required background modes and then set value App plays audio or streams audio/video using AirPlay

Signing & Capabilities

image

Add Background Modes,only need set the first option

Code

        
        let recordingSession = AVAudioSession.sharedInstance()
        do {
            try recordingSession.setCategory(AVAudioSession.Category.playAndRecord, # important
                                             mode: .default,
                                             policy: .default)
            
            try recordingSession.setActive(true)
        } catch {
            print("Cannot setup the Recording")
        }

Set AVAudioSession's category to AVAudioSession.Category.playAndRecord