首页 文章

声音仅在iOS中使用AVAudioEngine首次播放

提问于
浏览
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()
    }
}

1 回答

  • 0

    问题在于你的playSound功能 .

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

    只有在玩家已玩的情况下,您才会尝试播放该播放器 . 所以没有任何意义 . 你可以删除这些行,只需使用它 .

    audioPlayer.play()
    

相关问题