2014-10-31 134 views
5

我无法用AVAudioPCMBuffer播放声音(虽然我可以用AVAudioFile播放)。 我得到这个错误。如何用AVAudioPCMBuffer播放声音

错误: AVAudioBuffer.mm:169: - [AVAudioPCMBuffer initWithPCMFormat:frameCapacity:]:需要的条件是假的:isCommonFormat

这里是我下面的代码,我会很感激你的帮忙。

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 

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

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

    audioEngine.attachNode(audioFilePlayer) 

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

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

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

    var engineError: NSError? 
    audioEngine.startAndReturnError(&engineError) 

    audioFilePlayer.play() 
} 

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

} 

回答

5

只是让我分享一下,虽然我不完全理解,但这种方式有点奏效。

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

} 
2

问题是您将PCM缓冲区的格式设置为非PCM格式。因此,您需要使用AVAudioFile的processingFormat创建您的AVAudioPCMBuffer