2015-09-27 40 views
0

我從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

已解決。我讀過的文檔和想通了,在您讀文件到緩衝器

self.audioFile.readIntoBuffer(audioFileBuffer) 

文件框的位置被讀取的幀數前進。

所以下次沒有幀要讀。所以我重置框架的位置像這樣

self.audioFile.framePosition = 0 

希望這會幫助別人。