AVAudioPlayerNode keeps repeating sound

时间:2019-03-17 22:23:30

标签: ios swift avfoundation avaudioplayer avaudioplayernode

I am currently in the process of creating a music application, and will allow the user to change the pitch and speed at which the sound is being played. I am using buttons as the sound initiators, and every time a button is pressed, the corresponding sound will start playing.

This is my current code :

 audioPlayer.stop()
    engine.stop()
    pitchControl.pitch = 0.0
    engine = AVAudioEngine()
    audioPlayer.volume = 1.0

    let precursor = audioFiles[audioFileLinks[sender.tag]]
    let path = Bundle.main.path(forResource: precursor, ofType: "mp3")!
    let url = NSURL.fileURL(withPath: path)
    let file = try? AVAudioFile(forReading: url)
    let buffer = AVAudioPCMBuffer(pcmFormat: file!.processingFormat, frameCapacity: AVAudioFrameCount(file!.length))

    do {  
           try file!.read(into: buffer!)
        } catch _ {}
        engine.attach(audioPlayer)
        engine.attach(pitchControl)
        engine.attach(speedControl)
        engine.connect(audioPlayer, to: speedControl, format: buffer?.format)
        engine.connect(speedControl, to: pitchControl, format: buffer?.format)
        engine.connect(pitchControl, to: engine.mainMixerNode, format:  buffer?.format)        
        engine.prepare()
        do {
           try engine.start()
        } catch _ {}

        audioPlayer.play()

The point of this code is to get which audio track to play based on the tag of the button pressed by the user. The issue that I am having is that every time I press a button, it will play the sound but it keeps playing the sound indefinitely, even though the actual .mp3 file is only 2 seconds long. I am not sure what I am doing wrong. I do not think I am doing anything wrong, I feel that I am just not setting some value correctly.

All help is appreciated! Thank You in advance!

0 个答案:

没有答案