我正在使用以下代码录制音频文件。
let audioFilename = getDocumentsDirectory().appendingPathComponent("tt.mp4")
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
do {
audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
} catch {
print(" startRecording fail ")
}
现在,当用户停止录制时,我想将音频文件保存在base64字符串中。我正在尝试使用以下代码:
let audioData = try? Data(contentsOf: (audioRecorder?.url)!)
let encodedString = audioData?.base64EncodedString()
print(" data \(encodedString)")
//"AAAAGGZ0eXBtcDQyAAAAAG1wNDJpc29t"
现在我正在尝试播放字符串:
let player = try? AVAudioPlayer(data:(encodedString?.data(using: String.Encoding.init(rawValue: 0)))!)
player?.prepareToPlay()
player?.play()
它没有玩。我失踪的地方?
答案 0 :(得分:2)
您的上一个代码段中出现错误,您尝试将base64编码的字符串转换回原始数据。
我没有尝试使用实际音频数据运行代码,但这至少应该可以解决您的数据转换错误:
if let encodedString = encodedString, let data = Data(base64Encoded: encodedString) {
let player = try? AVAudioPlayer(data: data)
player?.prepareToPlay()
player?.play()
}