Can't encode an Audio file to Base64?

血红的双手。 提交于 2019-12-11 10:55:22

问题


Objective: Dialog Flow Voice Bot Api

I need to send a wav file to the Dialog Flow Api and the format and settings were pre-defined.

  • So I recorded an audio using AVAudioRecorder in .wav format using following settings
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)
    }
}
  • Then I tried to convert it into Base64 audio format
let outputFile = try Data.init(contentsOf: fileUrl)
let base64String = outputFile.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
print(base64String)

So whenever I try to decode that encoded string, using an online converter, it displays some corrupted bytes

Thoughts??


回答1:


So I've found the answer to the question. The reason my byte array wasn't able to maintain correct headers was because of a key which I omitted in the settings variable

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

It was given in the docs that if you won't provide the settings i.e.

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

then

❌ AVAudio recorder will automatically prepare the file from the Format defined in the file. ❌

But turns out, that didn't help either 😫

So whilst I was playing with the settings, I found this very important key AVAudioFileTypeKey, which helped in maintaining the correct headers and thus a valid .wav file 😎

This is how a wav file with Valid headers look like



来源:https://stackoverflow.com/questions/58371778/cant-encode-an-audio-file-to-base64

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!