我下面的那个球员发出一声短促的哔哔声。但是,“ Player.shared.play()”第一次只能播放一次。 我无法按需再次触发它。 任何帮助将不胜感激。
import Foundation
import AudioKit
class Player {
static let shared = Player()
let osc = AKOscillator()
let env:AKAmplitudeEnvelope
var panner = AKPanner()
init() {
osc.amplitude = 0.3
env = AKAmplitudeEnvelope(osc)
env.attackDuration = 0.01
env.decayDuration = 0.01
env.sustainLevel = 0.0
env.releaseDuration = 0.01
panner = AKPanner(env)
AudioKit.output = panner
try! AudioKit.start()
osc.start()
env.start()
panner.start()
}
func play() {
osc.stop()
osc.start()
env.stop()
env.start()
}
}
答案 0 :(得分:0)
@ jl303,
由于某些原因,您必须在振荡器和包络的启动和停止之间增加一个延迟。我以这样的DispatchQueue延迟添加了它:
func playOsc() {
osc.start()
env.start()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [unowned self] in
self.osc.stop()
self.env.stop()
}
}
以下是上下文中经过修订的Player类:
import Foundation
import AudioKit
class Player {
static let sharedInstance = Player()
let osc = AKOscillator()
let env: AKAmplitudeEnvelope
var panner = AKPanner()
init() {
AKSettings.bufferLength = .medium
AKSettings.playbackWhileMuted = true
do {
try AKSettings.setSession(category: .playAndRecord, with: [.defaultToSpeaker, .allowBluetooth, .mixWithOthers])
} catch {
AKLog("Could not set session category.")
}
osc.amplitude = 0.3
env = AKAmplitudeEnvelope(osc)
env.attackDuration = 0.01
env.decayDuration = 0.01
env.sustainLevel = 0.0
env.releaseDuration = 0.01
panner = AKPanner(env)
AudioKit.output = panner
try! AudioKit.start()
}
func playOsc() {
osc.start()
env.start()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [unowned self] in
self.osc.stop()
self.env.stop()
}
}
}
以下是ViewController
,可根据命令触发振荡器声音:
import UIKit
class ViewController: UIViewController {
var player = Player.sharedInstance
@IBOutlet weak var oscPlayStopButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setUpButtonStyle()
}
fileprivate func setUpButtonStyle() {
oscPlayStopButton.layer.cornerRadius = 12.0
oscPlayStopButton.layer.borderColor = UIColor.systemBlue.cgColor
oscPlayStopButton.layer.borderWidth = 1.0
}
@IBAction func playOscAction(_ sender: UIButton) {
player.playOsc()
}
}
您可以在此处下载Xcode项目: