gpt4 book ai didi

swift - 如何使用 AVAudioPCMBuffer 播放声音

转载 作者:搜寻专家 更新时间:2023-10-30 22:10:51 38 4
gpt4 key购买 nike

我无法使用 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.
}

}

最佳答案

让我分享一下,虽然我不完全理解,但它以某种方式起作用。

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

}

关于swift - 如何使用 AVAudioPCMBuffer 播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26670756/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com