Swift。声音不播放第二次

Swift. Sound don't play for the second time

我完成了 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

希望这会对某人有所帮助。