Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Help required scaling a Sinewave please?

LP25LP25 Member Posts: 2
Firstly I apologise if this has been addressed elsewhere - I tried to search but I got an error so after flicking through several pages (and having spent about 3 weeks searching the whole of the internet for help with this) and over 40 hours trying to sort the problem myself, I have resorted to asking on here.

I am REALLY new to programming and also very dumb. I try so hard but just always struggle. With everything. I was set an assignment which I couldn't do and therefore failed. I am still determined to do this assignment (even though it won't be marked I need to understand how it works), predominantly on my own, but I have hit a massive snag which has prevented me from completing it. The assignment was to create a raw mono audio file with user-defined frequency and sample rate. I have done this, but some frequencies cause clipping when the file is opened in Audacity, which is what I'm testing it in. I was hoping there is a way of "scaling" the sine wave so that it didn't clip? I would really appreciate any advice you have (other than "Give up now"), Thank you.
The code is here:

//Programme to generate a sine wave in a raw mono audio file.
using namespace std;

//Defined Constants
const double pi=3.141592;
const unsigned short int Samplength=2;
const unsigned short int amp=1;

//Defined Variables
unsigned short int Samplerate;
float sinewav(float,float);
float tone;

int main ()
//The user makes their choices here.
cout<<"This programme enables you to create a raw mono audio file.
cout<<"You may choose the frequency, the samplerate and the number of harmonics.
cout<<"What frequency would you like your tone to be?
cin>> tone;
cout<<"Thank you. You have chosen the frequency:" <<tone<<".
cout<<"What Samplerate would you like to set for your file?
cin>> Samplerate;
cout<<"Thank you. You have chosen the Samplerate:" <<Samplerate<<".
//The file is opened here.
FILE *o;
if ((o = fopen("123123.raw","wb")) == NULL)
printf ("Error creating file 123123.raw");
return 1;
float y;
for(int i=0;i<Samplength*Samplerate;++i)
//Is there something I could put here to scale it?
return 0;

float sinewav(float frequency, float timepoint)
return sin(2.0*pi*frequency*timepoint/Samplerate);
//I tried * this by 0.5 to ensure no clipping but obviously it still clipped at some of the higher frequencies.


  • Pelle-48Pelle-48 Member Posts: 43
    All I can help you with is the samplerate. It must be much higher than the tone. samplerate >4*tone should work
  • LP25LP25 Member Posts: 2
    Hi, Thank you for your reply but at the moment even when the frequency is only a tenth of the Sample Rate it creates problems so it must be something else I'm doing wrong somewhere. Oops!
Sign In or Register to comment.