在Swift iOS中播放PCM文件

问题描述 投票:5回答:1

我想使用AVAudioEngine播放pcm文件,使用Swift 2.0播放AVAudioPlayerNode。我是音频编程的新手,不了解我的代码问题:

    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)
    }
}

我能够构建代码,但是当我尝试运行它时,我收到以下错误:

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

我知道文件路径是正确的,文件存在。

有人知道我做错了什么吗?

ios swift audio
1个回答
0
投票

使用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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.