Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private func decodeAudioData(_ data: Data) -> AVAudioPCMBuffer? {
- guard let inputFormat = inputFormat else {
- NSLog("Error: Audio format is nil")
- return nil
- }
- var mp3StreamDescription = AudioStreamBasicDescription(
- mSampleRate: 44100,
- mFormatID: kAudioFormatMPEGLayer3,
- mFormatFlags: 0,
- mBytesPerPacket: 0,
- mFramesPerPacket: 1152,
- mBytesPerFrame: 0,
- mChannelsPerFrame: 2,
- mBitsPerChannel: 0,
- mReserved: 0
- )
- guard let mp3Format = AVAudioFormat(streamDescription: &mp3StreamDescription) else {
- fatalError("❌ Failed to create MP3 format")
- }
- let compressedBuffer = AVAudioCompressedBuffer(format: mp3Format, packetCapacity: 1, maximumPacketSize: data.count);
- data.copyBytes(to: compressedBuffer.data.assumingMemoryBound(to: UInt8.self), count: data.count)
- compressedBuffer.packetCount = 1
- print(compressedBuffer, data)
- let frameCapacity = UInt32(outputFormat.sampleRate);
- guard let pcmBuffer = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: frameCapacity) else { return nil }
- guard let converter = AVAudioConverter(from: mp3Format, to: outputFormat) else {
- fatalError("❌ Failed to create AVAudioConverter")
- }
- let inputBlock: AVAudioConverterInputBlock = { inNumPackets, outStatus in
- outStatus.pointee = .haveData
- return compressedBuffer
- }
- var error: NSError?
- converter.convert(to: pcmBuffer, error: nil, withInputFrom: inputBlock);
- if let error = error {
- NSLog("❌ Conversion error: \(error.localizedDescription)")
- return nil
- }
- print("✅ Successfully decoded MP3 → PCM")
- return pcmBuffer
- }
Advertisement
Add Comment
Please, Sign In to add comment