2

我有一个声音文件,它听成哔哔声,我必须反复播放这个声音,并根据某些条件改变它的音高。我正在使用 AVAudioEngine、AVAudioPlayerNode 和 AVAudioUnitTimePitch 来实现这个目标。我认为有两个按钮,即PlayStop。当我第一次按下播放按钮时,声音在重复播放,但是在单击停止按钮一次然后再次单击播放按钮后,声音没有播放并且也没有错误。我一直在研究这个问题很长时间,但无法得到解决方案,所以我来到了这里。你能帮我解决这个问题吗?或者我的问题还有其他替代解决方案吗?我的代码如下:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    let engine = AVAudioEngine()
    let audioPlayer = AVAudioPlayerNode()
    let pitchUnit = AVAudioUnitTimePitch()

    var avAudioFile: AVAudioFile!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let path = Bundle.main.path(forResource: "Beep", ofType: "wav")!
        let url = NSURL.init(fileURLWithPath: path)
        avAudioFile = try? AVAudioFile(forReading: url as URL)

        setup()
    }

    func setup() {
        engine.attach(audioPlayer)
        engine.attach(pitchUnit)
        engine.connect(audioPlayer, to: pitchUnit, format: nil)
        engine.connect(pitchUnit, to:engine.mainMixerNode, format: nil)

        try? engine.start()

        audioPlayer.volume = 1.0
        audioPlayer.play()

    }
    @IBAction func playSound(_ sender: UIButton) {

        pitchUnit.pitch = 1

        // interrupt playing sound if you have to
        if audioPlayer.isPlaying {
            audioPlayer.stop()
            audioPlayer.play()
        }
        let buffer = AVAudioPCMBuffer(pcmFormat: avAudioFile.processingFormat, frameCapacity: AVAudioFrameCount(avAudioFile.length))
        try? avAudioFile.read(into: buffer!)
        audioPlayer.scheduleBuffer(buffer!, at: nil, options: AVAudioPlayerNodeBufferOptions.loops, completionHandler: nil)
    }

    @IBAction func stopSound(_ sender: UIButton) {
        audioPlayer.stop()
    }
}
4

1 回答 1

0

问题在于你的 playSound 函数。

// interrupt playing sound if you have to
if audioPlayer.isPlaying {
    audioPlayer.stop()
    audioPlayer.play()
}

只有在播放器已经播放时,您才尝试播放播放器。所以这没有任何意义。您可以删除这些行,并且可以简单地使用它。

 audioPlayer.play()
于 2018-05-18T10:06:28.490 回答