Creating Square, Saw and Sine Sample and Writing to AIFF File - Large Number Problems

Trying to generate square, saw and sin wav in code and then save to AIFF file based on Chris Adam's Learning Core Audio book. I'm working, but I'm confused as to why I don't need to convert the sample to .bigEndian

in Swift, but do you need to convert to Obj-C?

This is what the working code looks like in Obj-C:

SInt16 sample = CFSwapInt16HostToBig ((( i / wavelengthInSamples) * 
SHRT_MAX *2) - SHRT_MAX); 

      

This is what the working code looks like in Swift2:

var sample = Int16(((Double(i) / wavelengthInSamples) 
* Double(Int16.max) * 2) - Double(Int16.max))

      

This is what the Swift playground graph looks like if I leave .bigEndian

swift playground saw wave

If I add .bigEndian

after conversion to Int16()

and send to AudioFileWriteBytes, the generated sound won't sound correct:

var sample = Int16(((Double(i) / wavelengthInSamples) 
* Double(Int16.max) * 2) - Double(Int16.max)).bigEndian
AudioFileWriteBytes(audioFile, 0, Int64(sampleCount * 2), &bytesToWrite, &sample)

      

Full source here : https://gist.github.com/justinlevi/7a846070ee6e7e245cc3

Here are the links to the generated audio files. For some reason, the volume on a square wave is really low.

The next question . Why would a square wave be so much quieter compared to a saw or sins?

SOURCE: Adamson, Chris; Avila, Kevin (2012-04-03). Learning Core Audio: A Practical Guide to Audio Programming for Mac and iOS (Kindle Locations 1063-1073). Pearson's education. Kindle Edition.

+3


source to share


2 answers


Ugh ... @jaybers totally made me realize that AIFF files are written as littleEndian, so the plots looked like this. I saw these graphs in the playground when I added .bigEndian

to the sample. I updated the github project above and now everything looks as expected. The square wave is also as loud as the other samples ...

Big Endian AIFF Graphs



Here are the new audio files from .bigEndian Conversion.

0


source


For your follow up question, the mean RMS power of a square wave is higher than a sine wave. The square wave spends most of its time at its maximum peak amplitude. See wikipedia and stack exchange for details .

Your sine wave, saws and square wave files that you downloaded are not the signals you expect. They seem to repeat functions, but the waveforms are not clean. I discovered waveforms in audacity. The upper part is the sine. The middle one is a saw and the bottom one is a square. You can see that the amplitude is going down the square wave (almost illegible). If the signals were correct, the square wave would be much louder.



enter image description here

+1


source







All Articles