Reputation: 1941
I am recording an audio file using following code.
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 ")
}
Now when user stops the recording I want to save the audio file in a base64 string. I am trying with the following code:
let audioData = try? Data(contentsOf: (audioRecorder?.url)!)
let encodedString = audioData?.base64EncodedString()
print(" data \(encodedString)")
//"AAAAGGZ0eXBtcDQyAAAAAG1wNDJpc29t"
Now I am trying to play the string:
let player = try? AVAudioPlayer(data:(encodedString?.data(using: String.Encoding.init(rawValue: 0)))!)
player?.prepareToPlay()
player?.play()
It's not playing. Where I am missing?
Upvotes: 3
Views: 2069
Reputation: 1340
There's an error in your last code snippet where you try to convert the base64 encoded string back to raw data.
I haven't tried running the code with actual audio data, but this should at least fix your data conversion error:
if let encodedString = encodedString, let data = Data(base64Encoded: encodedString) {
let player = try? AVAudioPlayer(data: data)
player?.prepareToPlay()
player?.play()
}
Upvotes: 4