# Why did my sine wave turn into a square wave when written to a WAV file in Octave?

I am trying to use Octave to generate a pure sine wave. The code for the same is as follows:

x = 10.*sin(2*pi*(300/16000)*(0:1:400));
The sampling rate is 16000Hz, the sine wave is at 300 Hz. I write the above wave to a file using wavwrite like so:
wavwrite(x, 16000, 16, "temp.wav")

When I try to read it back into a variable, like so:
y = wavread('temp.wav');, I get square waves upon plotting y.
I have checked the sine wave and the period indicates a frequency of 300Hz.

How can a pure sine wave become a square wave on simply writing and reading? Or am I going wrong somewhere?

## 1 Answer

x is being clipped and that is why y looks like a square wave. When writing x to disk using wavwrite, the samples of x are stored in 16 bits Q15 fixed-point format. That means your data must be in range -1 to +1 (in principle +1 minus one lsb). Therefore, x must be normalized to be in this range before calling wavwrite in order to avoid clipping.

• thanks! that was the problem.. funny thing.. i always neglect to look at such problems as normalization issues. :( – Sriram Oct 19 '11 at 8:04
• @Sriram I had the same problem(s) until I realized what was going on with the normalization. Although I seem to remember now all bit-widths needed normalization for writing to .wav files... – Spacey Oct 20 '11 at 1:11
• That should read "...NOT all bit-widths..." btw. – Spacey Oct 20 '11 at 21:21