通过 AVAudioRecorder 在 WatchOS 上录制音频
Recording audio on WatchOS over AVAudioRecorder
有没有相关的示例代码或教程?我发现自 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
添加到您的 phone 配套应用 Info.plist
.
有没有相关的示例代码或教程?我发现自 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
添加到您的 phone 配套应用 Info.plist
.