我有一个声音文件,它听起来是哔哔声,我必须根据某些条件改变它的音高重复播放这个声音。我正在使用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()
}
}
答案 0 :(得分:0)
问题在于你的playSound功能。
#text
只有在播放器播放时才试播。所以没有任何意义。你可以删除这些行,只需使用它。
// interrupt playing sound if you have to
if audioPlayer.isPlaying {
audioPlayer.stop()
audioPlayer.play()
}