在WatchOS 4上录制音频

时间:2017-07-10 15:06:18

标签: swift avaudioengine watch-os-4

在WWDC17上,WatchOS 4宣布了新的录制功能。 我一直试图获得PCM阵列,但我没有成功。

目前我尝试使用以下代码:

检查AudioSession:

override func awake(withContext context: Any?) {
    super.awake(withContext: context)

    let recordingSession = AVAudioSession.sharedInstance()

    do {
        try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
        try recordingSession.setActive(true)
        recordingSession.requestRecordPermission() { [unowned self] allowed in
            DispatchQueue.main.async {
                if allowed {
                    self.recordingSessionSuccessfulPermission()
                } else {
                    self.recordingSessionFailPermission()
                }
            }
        }
    } catch {
        self.recordingSessionFailPermission()
    }
}

开始记录:

@IBAction func startRecordButton() {
    label.setText("start record")
    let audioEngine = AVAudioEngine.init()
    let inputNode = audioEngine.inputNode
    let format = inputNode.inputFormat(forBus: 0)
    inputNode.installTap(onBus: 0, bufferSize: 8000, format: format) { (buf, wheb) in
        self.label.setText("It is working")
    }

    audioEngine.prepare()
    do {
        try audioEngine.start()
    } catch {
        // Handle error...
    }
}

此代码抛出错误:

[audiocomp] 178: registration server connection invalidated
[audiocomp] 170: registration server proxy error: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.audio.AudioComponentRegistrar was invalidated." UserInfo={NSDebugDescription=The connection to service named com.apple.audio.AudioComponentRegistrar was invalidated.}

1 个答案:

答案 0 :(得分:2)

必须在Action之外创建AudioEngine对象。

例如:

class MyClass: WKInterfaceController {
    private var audioEngine = AVAudioEngine()