gpt4 book ai didi

swift - 如何在 AudioKit 中使用包络重放振荡器?

转载 作者:行者123 更新时间:2023-11-28 07:20:26 26 4
gpt4 key购买 nike

下面的播放器会发出一声短促的哔哔声。然而,“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()
}

}

最佳答案

@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 项目:

https://github.com/markjeschke/osc-player

关于swift - 如何在 AudioKit 中使用包络重放振荡器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58358480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com