我不能用 AVAudioPCMBuffer 播放声音(虽然我可以用 AVAudioFile 播放)。我得到了这个错误。
错误: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.
}
}