【问题标题】:Swift. Sound don't play for the second time迅速。第二次没有声音
【发布时间】:2015-09-27 19:09:46
【问题描述】:

我在 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()

}

【问题讨论】:

    标签: ios swift avfoundation


    【解决方案1】:

    解决了。我已经阅读了文档并确定了您将读取文件放入缓冲区的位置

    self.audioFile.readIntoBuffer(audioFileBuffer)
    

    文件帧位置提前读取的帧数。

    所以下次没有要读取的帧。所以我像这样重置框架位置

    self.audioFile.framePosition = 0
    

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

    【讨论】:

      猜你喜欢
      • 2015-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      相关资源
      最近更新 更多