斯威夫特。声音不第二次播放
问题描述:
我从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()
}
答
已解决。我读过的文档和想通了,在您读文件到缓冲器
self.audioFile.readIntoBuffer(audioFileBuffer)
文件框的位置被读取的帧数前进。
所以下次没有帧要读。所以我重置框架的位置像这样
self.audioFile.framePosition = 0
希望这会帮助别人。