无法将音频文件编码为Base64吗?

问题描述 投票:1回答:1

目标:对话流程语音Bot Api

我需要将wav文件发送到Dialog Flow Api,并且格式和设置是预先定义的。

  • 所以我以AVAudioRecorder格式使用.wav录制了音频,使用以下设置
audioFilename = getDocumentsDirectory().appendingPathComponent("input.wav")

let settings: [String: Any] = [
    AVFormatIDKey: Int(kAudioFormatLinearPCM),
    AVSampleRateKey: 16000,
    AVNumberOfChannelsKey: 2,
    AVLinearPCMBitDepthKey: 16,
    AVLinearPCMIsBigEndianKey: false,
    AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue
]

do {
    audioRecorder = try AVAudioRecorder(url: audioFilename!, settings: settings)
    audioRecorder.isMeteringEnabled = true
    audioRecorder.prepareToRecord()
    audioRecorder.delegate = self
    audioRecorder.record()
    recordButton.setTitle("Tap to Stop", for: .normal)
} catch {
    print(error.localizedDescription)
    finishRecording(success: false)
    }
}
  • 然后我尝试将其转换为Base64音频格式
let outputFile = try Data.init(contentsOf: fileUrl)
let base64String = outputFile.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
print(base64String)

因此,每当我尝试使用online converter解码该编码的字符串时,它都会显示一些损坏的字节Decoded output

想法?

ios wav swift4.2 voice-recording
1个回答
1
投票

因此,我找到了问题的答案。我的字节数组无法维护正确的标头的原因是因为我在settings变量中省略了一个键

AVAudioFileTypeKey: kAudioFileWAVEType
    let settings: [String: Any] = [
      AVSampleRateKey: 16000,
      AVNumberOfChannelsKey: 1,
      AVAudioFileTypeKey: kAudioFileWAVEType,  //MANDATORY
      AVFormatIDKey: kAudioFormatLinearPCM,
      AVLinearPCMIsBigEndianKey: false,
      AVLinearPCMIsNonInterleaved: true,
      AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

[中给出的是,如果您不提供设置,即

audioRecorder = try AVAudioRecorder(url: audioFilename!, settings: [:] /*empty settings*/)

然后

❌AVAudio刻录机将根据文件中定义的

格式

自动准备文件。 ❌但是事实证明,

也没有帮助😫

因此,在我使用设置的同时,我发现了这个[[非常重要AVAudioFileTypeKey,它有助于维护正确的标题并因此保持有效的.wav文件😎

这是带有有效标题的wav文件的外观A valid file

© www.soinside.com 2019 - 2024. All rights reserved.