我不能用AVAudioPCMBuffer播放声音(虽然我可以用AVAudioFile播放)。我得到了这个错误。
错误: AVAudioBuffer.mm:169:-AVAudioPCMBuffer initWithPCMFormat:frameCapacity::必需条件为false: 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.
}
}发布于 2014-11-01 11:35:30
让我分享一下,这是有效果的,尽管我不能完全理解。
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.
}
}发布于 2014-11-04 09:12:35
问题是您正在将PCM缓冲区的格式设置为非PCM格式。因此,您需要使用AVAudioFile的processingFormat创建您的AVAudioPCMBuffer。
发布于 2019-08-11 07:42:14
在使用AVAudioPCMBuffer()时,如果您尝试使用非mixer.outputFormat(forBus: 0)的pcmFormat,则会出现奇怪的错误
它不会接受单声道格式,它会抱怨混音器的输出格式和你的格式之间的不匹配,即使你描述它们是完全相同的,它也不会产生错误来确切地解释问题是什么。
https://stackoverflow.com/questions/26670756
复制相似问题