Skip to content

Instantly share code, notes, and snippets.

@renarl
Forked from yenrab/pure_tone.swift
Created November 14, 2022 17:33
Show Gist options
  • Save renarl/69cdf37b698b3b27c3e76b5b45231d11 to your computer and use it in GitHub Desktop.
Save renarl/69cdf37b698b3b27c3e76b5b45231d11 to your computer and use it in GitHub Desktop.

Revisions

  1. @yenrab yenrab revised this gist May 23, 2021. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion pure_tone.swift
    Original file line number Diff line number Diff line change
    @@ -26,7 +26,7 @@ Copyright (c) 2021 Lee Barney
    import Foundation
    import AVFoundation

    func playPureTone(frequencyInHz: Int, amplitude: Float, durationInMillis: Int, completionBlock: @escaping ()->Void) {
    func playPureTone(frequencyInHz: Int, amplitude: Float, durationInMillis: Int, completion: @escaping ()->Void) {
    //Use a semaphore to block until the tone completes playing
    let semaphore = DispatchSemaphore(value: 1)
    //Run async in the background so as not to block the current thread
  2. @yenrab yenrab created this gist May 23, 2021.
    84 changes: 84 additions & 0 deletions pure_tone.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,84 @@
    //
    //
    // Swift Pure Tone Generation
    //
    /*
    Copyright (c) 2021 Lee Barney
    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation the
    rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the Software
    is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.


    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
    INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
    PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
    CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
    OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    */

    import Foundation
    import AVFoundation

    func playPureTone(frequencyInHz: Int, amplitude: Float, durationInMillis: Int, completionBlock: @escaping ()->Void) {
    //Use a semaphore to block until the tone completes playing
    let semaphore = DispatchSemaphore(value: 1)
    //Run async in the background so as not to block the current thread
    DispatchQueue.global().async {
    //Build the player and its engine
    let audioPlayer = AVAudioPlayerNode()
    let audioEngine = AVAudioEngine()
    semaphore.wait()//Claim the semphore for blocking
    audioEngine.attach(audioPlayer)
    let mixer = audioEngine.mainMixerNode
    let sampleRateHz = Float(mixer.outputFormat(forBus: 0).sampleRate)

    guard let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatFloat32, sampleRate: Double(sampleRateHz), channels: AVAudioChannelCount(1), interleaved: false) else {
    return
    }
    // Connect the audio engine to the audio player
    audioEngine.connect(audioPlayer, to: mixer, format: format)


    let numberOfSamples = AVAudioFrameCount((Float(durationInMillis) / 1000 * sampleRateHz))
    //create the appropriatly sized buffer
    guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: numberOfSamples) else {
    return
    }
    buffer.frameLength = numberOfSamples
    //get a pointer to the buffer of floats
    let channels = UnsafeBufferPointer(start: buffer.floatChannelData, count: Int(format.channelCount))
    let floats = UnsafeMutableBufferPointer<Float>(start: channels[0], count: Int(numberOfSamples))
    //calculate the angular frequency
    let angularFrequency = Float(frequencyInHz * 2) * .pi
    // Generate and store the sequential samples representing the sine wave of the tone
    for i in 0 ..< Int(numberOfSamples) {
    let waveComponent = sinf(Float(i) * angularFrequency / sampleRateHz)
    floats[i] = waveComponent * amplitude
    }
    do {
    try audioEngine.start()
    }
    catch{
    print("Error: Engine start failure")
    return
    }

    // Play the pure tone represented by the buffer
    audioPlayer.play()
    audioPlayer.scheduleBuffer(buffer, at: nil, options: .interrupts){
    DispatchQueue.main.async {
    completionBlock()
    semaphore.signal()//Release one claim of the semiphore
    }
    }
    semaphore.wait()//Wait for the semiphore so the function doesn't end before the playing of the tone completes
    semaphore.signal()//Release the other claim of the semiphore
    }
    }