Loading a previously saved audio file as base64 st

2019-07-03 04:11发布

I record and save an audio file, this works and plays in the app as expected. After the recording, however, I try to load it so I can pass the audio into a JSON object, but can't open it.

I get the following error:

The file “audio.m4a” couldn’t be opened because the text encoding of its contents can’t be determined.

This is call I'm making:

do {
     let audioData =  try NSData(contentsOfFile: String(contentsOf: audioURL!))
} catch {
     print error
}

Any ideas how I can load the audio data as from the file in base64 encoding?

Thanks

标签: ios swift swift3
2条回答
Fickle 薄情
2楼-- · 2019-07-03 04:24

The problem is that you are using the wrong method. The audio data it is not a string it is a collection of bytes (an array of UInt8). To read your audio data you need to use the Data initializer Data(contentsOf: audioURL) and convert this data to base64 string using Data instance method base64EncodedString.

if let base64String = try? Data(contentsOf: audioURL).base64EncodedString() {
    print(base64String)
}
查看更多
甜甜的少女心
3楼-- · 2019-07-03 04:48

You didn't explain how do you save your file, so i can only assume (according to file extension), that you are not saving it as base64 string. Please refer to first answer of this question. To check if you save audio file as base64 string correctly. But still you can use other way. At first load data:

let audioData =  try Data(contentsOf: audioURL!)

Then convert it to base64 string:

let encodedString = audioData.base64EncodedString()
查看更多
登录 后发表回答