我从Udacity课程(Pitch Perfect)
做了一个简单的任务我有一个录制声音的屏幕。录制后我保存文件并将其传递给第二个屏幕。
在第二个屏幕上,我有几个以不同方式播放声音的按钮。我有一个播放音调的功能。
问题是,当我第一次播放声音时播放此功能,但是第二次没有声音。
我被困住了。
func playSoundWithPitchRate(pitch: Float) {
self.audioPlayer.stop()
self.audioEngine.stop()
self.audioEngine.reset()
let audioPlayerNode = AVAudioPlayerNode()
self.audioEngine.attachNode(audioPlayerNode)
let changePitchEffect = AVAudioUnitTimePitch()
changePitchEffect.pitch = pitch
self.audioEngine.attachNode(changePitchEffect)
self.audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil)
self.audioEngine.connect(changePitchEffect, to: self.audioEngine.outputNode, format: nil)
let audioFileBuffer = AVAudioPCMBuffer(PCMFormat: self.audioFile.processingFormat, frameCapacity: AVAudioFrameCount(self.audioFile.length) )
do{
try self.audioFile.readIntoBuffer(audioFileBuffer)
} catch let err as NSError {
print("self.audioFile.readIntoBuffer(audioFileBuffer)")
print(err.localizedDescription)
}
audioPlayerNode.scheduleBuffer(audioFileBuffer, atTime: nil, options: .Interrupts) { () -> Void in
// reminder: we're not on the main thread in here
dispatch_async(dispatch_get_main_queue()) {
self.stopPlayButton.enabled = false
self.makeSoundEffectButtonsEnabled(true)
}
}
do {
try audioEngine.start()
} catch let err as NSError {
print("audioEngine.start()")
print(err.localizedDescription)
}
audioPlayerNode.play()
}
答案 0 :(得分:0)
解决。我已经阅读了文档并想出了将文件读入缓冲区的位置
self.audioFile.readIntoBuffer(audioFileBuffer)
文件框架位置按读取的帧数提前。
所以下次没有帧可读。所以我像这样重置帧位置
self.audioFile.framePosition = 0
希望这会对某人有所帮助。