how to play sound with AVAudioPCMBuffer

那年仲夏 提交于 2019-12-03 14:01:31

just let me share, this worked somehow, though I don't understand fully.

import UIKit
import AVFoundation

class ViewController: UIViewController {

var audioEngine: AVAudioEngine = AVAudioEngine()
var audioFilePlayer: AVAudioPlayerNode = AVAudioPlayerNode()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    let filePath: String = NSBundle.mainBundle().pathForResource("test", ofType: "mp3")!
    println("\(filePath)")
    let fileURL: NSURL = NSURL(fileURLWithPath: filePath)!
    let audioFile = AVAudioFile(forReading: fileURL, error: nil)
    let audioFormat = audioFile.processingFormat
    let audioFrameCount = UInt32(audioFile.length)
    let audioFileBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: audioFrameCount)
    audioFile.readIntoBuffer(audioFileBuffer, error: nil)

    var mainMixer = audioEngine.mainMixerNode
    audioEngine.attachNode(audioFilePlayer)
    audioEngine.connect(audioFilePlayer, to:mainMixer, format: audioFileBuffer.format)
    audioEngine.startAndReturnError(nil)

    audioFilePlayer.play()
    audioFilePlayer.scheduleBuffer(audioFileBuffer, atTime: nil, options: nil, completionHandler: nil)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
Bob McCune

The problem is you're setting the format of your PCM buffer to a non-PCM format. Therefore, you need to create your AVAudioPCMBuffer with the AVAudioFile's processingFormat.

Andrew Hodel

When using an AVAudioPCMBuffer() you'll get strange errors if you try and use a pcmFormat that's not mixer.outputFormat(forBus: 0)

It will not accept mono channel formats, it will complain about mismatches between the mixer's output format and your format even if you've described them exactly the same and it won't produce errors that explain exactly what the problem is.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!