0

我目前正在创建一个音乐应用程序,并将允许用户更改播放声音的音高和速度。我使用按钮作为声音启动器,每次按下按钮时,都会开始播放相应的声音。

这是我当前的代码:

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

这段代码的重点是根据用户按下的按钮的标签来获取播放哪个音轨。我遇到的问题是,每次按下按钮时,它都会播放声音,但它会无限期地播放声音,即使实际的 .mp3 文件只有 2 秒长。我不确定我做错了什么。我不认为我做错了什么,我觉得我只是没有正确设置一些值。

感谢所有帮助!先感谢您!

4

0 回答 0