Playing PCM file in Swift iOS

I want to play a pcm file using AVAudioEngine and AVAudioPlayerNode with Swift 2.0. I am new to the audio program and don't understand the problem with my code:

var audioEngine: AVAudioEngine = AVAudioEngine() var audioFilePlayer: AVAudioPlayerNode = AVAudioPlayerNode() @IBAction func playButton(sender: AnyObject) { var file = "file7.pcm" var fileManager = NSFileManager.defaultManager() var wayToFile = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask) var passMusicFileURL: NSURL? if let documentPath: NSURL = wayToFile.first as NSURL! { let musicFile = documentPath.URLByAppendingPathComponent(file) passMusicFileURL = musicFile var audioFile = AVAudioFile() var audioBuffer = AVAudioPCMBuffer() do{ audioFile = try AVAudioFile(forReading: passMusicFileURL!) let audioFormat = audioFile.processingFormat let audioFrameCount = UInt32(audioFile.length) audioBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: audioFrameCount) } catch { print("error!!! ") } do { try audioFile.readIntoBuffer(audioBuffer) } catch _{ print("error") } var mainMixer = audioEngine.mainMixerNode audioEngine.attachNode(audioFilePlayer) audioEngine.connect(audioFilePlayer, to:mainMixer, format: audioBuffer.format) do { try audioEngine.start() } catch _{ print("error") } audioFilePlayer.play() audioFilePlayer.scheduleBuffer(audioBuffer, atTime: nil, options: AVAudioPlayerNodeBufferOptions.Loops, completionHandler: nil) } } 

I can create the code, but when I try to run it, I get the following error:

ERROR: [0x1a1b6e000] AVAudioFile.mm:32: AVAudioFileImpl: error 1954115647

I know that the file path is correct and the file exists.

Does anyone know what I'm doing wrong?

+5
source share
1 answer

use swift 4

  func playPCM(_ filefullpathstr: String) { do { let audioFile = try AVAudioFile(forReading: URL(fileURLWithPath: filefullpathstr)) let audioFormat = audioFile.processingFormat let audioFrameCount = UInt32(audioFile.length) let audioFileBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat, frameCapacity: audioFrameCount) try audioFile.read(into: audioFileBuffer!, frameCount: audioFrameCount) let mainMixer = audioEngine.mainMixerNode audioEngine.attach(audioFilePlayer) audioEngine.connect(audioFilePlayer, to:mainMixer, format: audioFileBuffer?.format) try audioEngine.start() audioFilePlayer.play() audioFilePlayer.scheduleBuffer(audioFileBuffer!, at: nil, options: [], completionHandler: { DispatchQueue.main.async { //do sth ui ... } }) } catch { debugPrint(#line, error) } } 
0
source

Source: https://habr.com/ru/post/1234100/


All Articles