【问题标题】:Can't encode an Audio file to Base64?无法将音频文件编码为 Base64?
【发布时间】:2020-02-10 18:47:56
【问题描述】:

目标:对话流语音机器人 API

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

  • 所以我使用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 解码该编码字符串时,它都会显示一些损坏的字节

想法??

【问题讨论】:

    标签: ios wav swift4.2 voice-recording


    【解决方案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
        ]
    

    docs 中给出了如果您不提供设置,即

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

    然后

    ❌ AVAudio 录音机将根据文件中定义的格式自动准备文件。 ❌

    但事实证明,这 也没有帮助 ?

    所以当我在玩设置时,我发现这个 非常重要AVAudioFileTypeKey,它有助于保持正确的标题,因此是一个有效的 .wav 文件?

    这是带有有效标题的 wav 文件的样子

    【讨论】:

      猜你喜欢
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 2015-09-18
      • 1970-01-01
      相关资源
      最近更新 更多