我有一个声音文件,它以哔声的形式收听,我必须反复播放此声音,并根据某些条件更改其音高。我正在使用 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/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |