我有一个声音文件,可以听见哔哔声,并且必须根据某些情况改变音调来重复播放此声音。我正在使用AVAudioEngine,AVAudioPlayerNode和AVAudioUnitTimePitch来实现此目标。我的视图中有两个按钮,分别是播放和停止。当我第一次按下“播放”按钮时,声音会反复播放,但是在单击“停止”按钮一次后再单击“播放”按钮后,声音不会播放,也不会出现错误。我一直在研究此问题很长时间,但无法获得解决方案,所以我来到了这里。您能帮我解决这个问题吗?还是我的问题有其他替代解决方案?我的代码如下:
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()
}
}
最佳答案
问题出在您的playSound函数中。
// interrupt playing sound if you have to
if audioPlayer.isPlaying {
audioPlayer.stop()
audioPlayer.play()
}
您尝试仅在播放器已经播放时播放它。所以这没有任何意义。您可以删除这些行,并且可以仅使用此行。
audioPlayer.play()
关于ios - 声音仅在iOS中使用AVAudioEngine首次播放,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49964740/