简体   繁体   中英

AudioKit-Oscillator starts with click-sound, the first time it is started

I got the problem, that the DynamicOscillator() is making a click-sound the first time it is used after the app is started. It sounds just like if the fade-in doesn't work, but I don't get why.

Here is my code:

import SwiftUI
import AVFoundation
import AudioKit
import SoundpipeAudioKit

struct Exercise1View: View {
    
    let osc = DynamicOscillator() //Oscillator from AudioKit
    let audioEngine = AudioEngine()
    
    var body: some View {
        Button {
            osc.setWaveform(Table(.sine)) // set osc-type to sine-wave
            osc.$frequency.ramp(to: 440, duration: 0) // set frequency of osc
            osc.amplitude = 0 // set amplitude to 0
            osc.start()
            osc.$amplitude.ramp(to: 1, duration: 0.01) //fade in, so there is no click sound
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { // wait 1 second
                osc.$amplitude.ramp(to: 0, duration: 0.01) //fade out, so there is no click sound
            }
        } label: { Text("play tone") }
        .onAppear {
            audioEngine.output = osc
            do {
                try audioEngine.start()
            } catch {
                print("could not start audioengine")
            }
        }
    }
}

If you have any idea, please let me know. Thanks a lot!

Set the oscillator amplitude to zero on init and then start it when you start the audio engine.

struct Exercise1View: View {

    let osc = DynamicOscillator(amplitude: 0) // Set amplitude to zero here
    let audioEngine = AudioEngine()

    var body: some View {
        Button {
            osc.setWaveform(Table(.sine)) 
            osc.$frequency.ramp(to: 440, duration: 0)
            osc.$amplitude.ramp(to: 1, duration: 0.01) 
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                osc.$amplitude.ramp(to: 0, duration: 0.01) 
            }
        } label: { Text("play tone") }
        .onAppear {
            audioEngine.output = osc
            do {
                osc.start() // Start Oscillator right away, manage playback with amplitude
                try audioEngine.start()
            } catch {
                print("could not start audioengine")
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM