Swift - create sine waves with high frequencies

458 views Asked by At

I have the following problem: for the sake of amplitude modulation, I want to generate a sine wave with a given frequency. For lower frequencies (such as 440 Hz) the algorithm works well, but dealing with high frequencies (for example 20.000 Hz), I get additional noises of lower frequencies, increasing with the time - I mean longer I play the signal, more and more unwanted frequencies appear - and the signal is thus distorted.

Here's the essence of my algorithm

    let methodStart = NSDate()
    
    let n = vDSP_Length(1024)

    let page: [Float] = (0 ..< n).map {_ in
        let val: Float = sin(2.0 * .pi * 20000.0 / 44100 * Float(index))
        index += 1
        return val
    }
    
    let methodFinish = NSDate()
    let executionTime = methodFinish.timeIntervalSince(methodStart as Date)
    print("Execution time: \(executionTime)")  // 0.0005 s

As you can see, I work with a loop - later the page array is used to generate the correspondent tone.

I did measure the execution time which looks like this:

Execution time: 0.0004639625549316406
Execution time: 0.000661015510559082
Execution time: 0.0005699396133422852
Execution time: 0.00047194957733154297
Execution time: 0.0005259513854980469
Execution time: 0.00047194957733154297
Execution time: 0.0005289316177368164

When we talk about the signal frequency of 20.000 Hz, the execution time should not be an issue, as during approx. 0.0005 s, a signal period fits more or less 10 times into the execution time range -> 1 : 20.000 = 0.00005.

My question: how can I achieve a pure signal? Should I work with pointers? If so, how can I do so in my case?

0

There are 0 answers