swift - 通过 AVAudioRecorder 在 WatchOS 上录制音频

标签 swift avfoundation watchkit watchos

有相关的示例代码或教程吗?我发现自 WatchOS 4.0 https://developer.apple.com/documentation/avfoundation/avaudiorecorder 起就支持 AVAudioRecorder 。但是当我尝试使用它时 - 它记录了 1 秒并且没有实际声音(只是噪音)。

这是我的代码:

let audioURL = self.getRecordedFileURL()
print(audioURL.absoluteString)

let settings = [
  AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
  AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]

do {
  recorder = try AVAudioRecorder(url: audioURL, settings: settings)
  recorder?.delegate = self
  recorder?.record()
} catch {
  finishRecording(success: false)
}

另外,我应该在这里使用 AudioSession 吗?如果是,是否需要requestRecordPermission以及如何处理?感谢您的帮助!

最佳答案

这个有效:

    let recordingName = "audio.m4a"
    let dirPath = getDirectory()
    let pathArray = [dirPath, recordingName]
    guard let filePath = URL(string: pathArray.joined(separator: "/")) else { return }

    let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                    AVSampleRateKey:12000,
                    AVNumberOfChannelsKey:1,
                    AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

    //start recording
    do {
        audioRecorder = try AVAudioRecorder(url: filePath, settings: settings)
        audioRecorder.delegate = self
        audioRecorder.record()
    } catch {
        print("Recording Failed")
    }
func getDirectory()-> String {
    let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    return dirPath
}

不要忘记将 NSMicrophoneUsageDescription 添加到您的手机配套应用 Info.plist 中。

关于swift - 通过 AVAudioRecorder 在 WatchOS 上录制音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56407339/

相关文章:

ios - 使用 NSURLSession 在 Apple Watch 上网络请求安静缓慢

ios - 在 Swift 3 中设置动画背景颜色

swift - 根据 scrollview 使用自动布局水平滚动更改 View 的高度和宽度

ios - 在运行 ios 13 的设备上,如果应用程序崩溃,则无法播放音频文件

ios - 在按钮上播放声音(AV 音频播放器)返回 nil 字符串参数

ios - 发送同步请求 :urlrequest returningResponse:&responce error:&error is unavilable in WatchOS2

watchkit - WKInterfaceLabel 的 Installed 和 Hidden 属性的区别

swift - 如果文本字段留空,如何恢复 "clearsOnBeginEditing(true) effect"(在开始编辑时删除旧值)?

ios - 如果我在 IOS Swift 上有位置坐标信息,我们如何检索 PlaceID

ios - Swift 中的自定义相机和裁剪图像