gpt4 book ai didi

ios - 在 Swift iOS 中播放 PCM 文件

转载 作者:搜寻专家 更新时间:2023-10-31 08:08:27 24 4
gpt4 key购买 nike

我想在 Swift 2.0 中使用 AVAudioEngine 和 AVAudioPlayerNode 播放一个 pcm 文件。我是音频编程的新手,不明白我的代码有什么问题:

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


@IBAction func playButton(sender: AnyObject) {

var file = "file7.pcm"
var fileManager = NSFileManager.defaultManager()

var wayToFile = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
var passMusicFileURL: NSURL?

if let documentPath: NSURL = wayToFile.first as NSURL! {
let musicFile = documentPath.URLByAppendingPathComponent(file)

passMusicFileURL = musicFile

var audioFile = AVAudioFile()
var audioBuffer = AVAudioPCMBuffer()

do{
audioFile = try AVAudioFile(forReading: passMusicFileURL!)
let audioFormat = audioFile.processingFormat
let audioFrameCount = UInt32(audioFile.length)

audioBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: audioFrameCount)

} catch {
print("error!!! ")
}

do {
try audioFile.readIntoBuffer(audioBuffer)
} catch _{
print("error")
}

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

do {
try audioEngine.start()
} catch _{

print("error")
}

audioFilePlayer.play()
audioFilePlayer.scheduleBuffer(audioBuffer, atTime: nil, options: AVAudioPlayerNodeBufferOptions.Loops, completionHandler: nil)
}
}

我能够构建代码,但是当我尝试运行它时出现以下错误:

错误:[0x1a1b6e000] AVAudioFile.mm:32:AVAudioFileImpl:错误 1954115647

我知道文件路径正确,文件存在。

有人知道我做错了什么吗?

最佳答案

使用 Swift 4

 func playPCM(_ filefullpathstr: String) {
do {
let audioFile = try AVAudioFile(forReading: URL(fileURLWithPath: filefullpathstr))

let audioFormat = audioFile.processingFormat
let audioFrameCount = UInt32(audioFile.length)

let audioFileBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat, frameCapacity: audioFrameCount)

try audioFile.read(into: audioFileBuffer!, frameCount: audioFrameCount)

let mainMixer = audioEngine.mainMixerNode
audioEngine.attach(audioFilePlayer)
audioEngine.connect(audioFilePlayer, to:mainMixer, format: audioFileBuffer?.format)

try audioEngine.start()
audioFilePlayer.play()
audioFilePlayer.scheduleBuffer(audioFileBuffer!, at: nil, options: [], completionHandler: {

DispatchQueue.main.async {
//do sth ui ...
}
})
} catch {
debugPrint(#line, error)
}
}

关于ios - 在 Swift iOS 中播放 PCM 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33232721/

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