我正在尝试一个简单的例子,在iOS中使用Swift中的AVAudoiRecorder
录制音频,我创建了这个类:
import Foundation
import AVFoundation
class AudioRecorder: NSObject, AVAudioRecorderDelegate {
var audioRecorder: AVAudioRecorder?
var file: URL? = nil
func setupAudioSession() {
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(.playAndRecord, mode: .default)
try session.setActive(true)
try session.overrideOutputAudioPort(.speaker)
debugPrint("Listo todo")
} catch {
print("Error setting up audio session: \(error.localizedDescription)")
}
}
func startRecording() {
file = getDocumentsDirectory().appendingPathComponent("recording.wav")
let settings: [String: Any] = [
AVFormatIDKey: kAudioFormatLinearPCM,
AVSampleRateKey: 44100.0,
AVNumberOfChannelsKey: 2,
AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsFloatKey: false,
AVLinearPCMIsBigEndianKey: false
]
do {
audioRecorder = try AVAudioRecorder(url: file!, settings: settings)
audioRecorder?.delegate = self
audioRecorder?.prepareToRecord()
audioRecorder?.record()
} catch {
print("Error starting recording: \(error.localizedDescription)")
}
}
func stopRecording() {
audioRecorder?.stop()
}
private func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
// MARK: AVAudioRecorderDelegate
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if flag {
print("Recording was successful.")
} else {
print("Recording failed.")
}
}
}
字符串
视图调用setupAudioSession
,当按下按钮时,我调用startRecording
(在此之前,我用AVAudioSession.sharedInstance().requestRecordPermission
检查麦克风权限)。
当我按下stop时,我从audioRecorderDidFinishRecording
回调的日志中获得一条Recording was successful
消息。如果我尝试使用AVAudioPlayer
播放文件,我可以正确读取文件属性:
"Playing ... Optional(\"file:///var/mobile/Containers/Data/Application/0760DB3E-440E-4898-83A6-0888EC2EA399/Documents/recording.wav\")"
"Duration: 4.180997732426304"
"Format: <AVAudioFormat 0x281ce80f0: 2 ch, 44100 Hz, Int16, interleaved>"
"Current Time: 0.0"
"Volume: 1.0"
型
但是一点声音都没有。我还在Info.plist中设置了NSMicrophoneUsageDescription
来访问麦克风。
我在模拟器和真实的设备中试过,根本没有声音。此外,我已经下载了WAV文件,并在音频编辑器中检查,该文件是空的。
你知道我会错过什么吗看起来像一个真正的例子,所有的东西,我可以找到搜索是非常相似的。
1条答案
按热度按时间0x6upsns1#
好吧,我想我终于成功了。不是100%确定,但看起来我在AVAudioRecorder和AVAudioPlayer的示例保留方面遇到了一些问题。在确保示例未被销毁后,所有示例都将按预期开始工作。