在背景中播放音频时识别麦克风中的语音



我希望我的应用程序能够识别麦克风中的语音,并允许背景中的音频继续播放。

我的应用程序识别通过麦克风输入的语音并将其转换为文本。当我的应用程序启动时,它会关闭后台播放的任何音频。

当我的应用程序使用麦克风收听语音时,是否可以让背景音频继续播放?

剥离代码:

import UIKit
import Speech
class ViewController: UIViewController {
public private(set) var isRecording = false
private var audioEngine: AVAudioEngine!
private var inputNode: AVAudioInputNode!
private var audioSession: AVAudioSession!
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
override func viewDidLoad() {
super.viewDidLoad()
}

override public func viewDidAppear(_ animated: Bool) {
checkPermissions()
startRecording()
isRecording.toggle()
}

private func startRecording() {
guard let recognizer = SFSpeechRecognizer(), recognizer.isAvailable else {
handleError(withMessage: "Speech recognizer not available.")
return
}
recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
recognitionRequest!.shouldReportPartialResults = true
recognizer.recognitionTask(with: recognitionRequest!) { (result, error) in
guard error == nil else { self.handleError(withMessage: error!.localizedDescription); return }
guard let result = result else { return }
print(result.bestTranscription.segments)
}
audioEngine = AVAudioEngine()
inputNode = audioEngine.inputNode
let recordingFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, _) in
self.recognitionRequest?.append(buffer)
}
audioEngine.prepare()
do {
audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(.record, mode: .spokenAudio, options: .duckOthers)
try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
try audioEngine.start()
} catch {
handleError(withMessage: error.localizedDescription)
}
}
private func checkPermissions() {
SFSpeechRecognizer.requestAuthorization { authStatus in
DispatchQueue.main.async {
switch authStatus {
case .authorized: break
default: self.handlePermissionFailed()
}
}
}
}
private func handlePermissionFailed() {
// Present an alert asking the user to change their settings.
let ac = UIAlertController(title: "This app must have access to speech recognition to work.",
message: "Please consider updating your settings.",
preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Open settings", style: .default) { _ in
let url = URL(string: UIApplication.openSettingsURLString)!
UIApplication.shared.open(url)
})
ac.addAction(UIAlertAction(title: "Close", style: .cancel))
present(ac, animated: true)
}
private func handleError(withMessage message: String) {
// Present an alert.
let ac = UIAlertController(title: "An error occured", message: message, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}

当我运行我的应用程序,并且有音频在后台运行时,我的应用会暂停音频。我尝试退出应用程序并重新启动音频,但当我返回应用程序时,它再次暂停背景音频。我希望在我的应用程序使用麦克风收听时继续播放音频。

我试着把";选项:.duckOthers";但没有什么区别。

我相信我想做的是可能的。例如,Shazam可以在扬声器上播放歌曲,同时使用麦克风收听并识别

尝试.playAndRecord而不是.record

最新更新