Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Sine Wave  (Read 3232 times)

0 Members and 2 Guests are viewing this topic.

Foaly

  • Sr. Member
  • ****
  • Posts: 453
    • View Profile
Sine Wave
« on: February 24, 2012, 08:06:29 am »
Hi everybody,
I have a little problem. I am trying to write a little program that creates simple Sounds like a Sine wave or a Square wave. As for now everything is going quiet well. The only thing is that the output is not as I expected. It sounds right, but when I went to a program like Audacity and compared my output to their Sinewave (same with the Squarewave respectively) I noticed that my sound is one wavelength to short. I am not quiet sure why. I think it might be a rounding error... Can somebody please tell me whats wrong.
Thanks in advance,
Foaly

Code: [Select]
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
#include <vector>
#include <math.h>

#define sin_d(x) (sin((x)*M_PI/180))

int main()
{
    int SampleRate = 44100; // 44100 = CD-Quality
    int Frequency = 440; // 440 = A
    float Duration = 1; // in Seconds
    int LengthInSamples = SampleRate * Duration;


    sf::Int16 Samples[LengthInSamples];

    float dist = SampleRate / Frequency;
    int dist2 = dist / 2;
    int count = LengthInSamples / dist +1;

    for(int a = 0; a < count; a++)
    {
        for(int b = 0; b < dist; b++)
        {
            if(a * dist + b >= LengthInSamples)
            {
                break;
            }

//            //Sine Wave
//            Samples[a*int(dist)+b] = sin_d(b / dist * 360.f) * 32767;

//            // Square Wave
//            if(b < dist2)
//            {
//                Samples[a*int(dist) + b] = 32767;
//            }
//            else
//            {
//                Samples[a*int(dist) + b] = -32767;
//            }
        }
    }

    sf::SoundBuffer FinalBuffer;
    FinalBuffer.LoadFromSamples(Samples, LengthInSamples, 1, SampleRate);
    FinalBuffer.SaveToFile("output.wav");

    return 0;
}

coldkillerlips

  • Newbie
  • *
  • Posts: 4
    • View Profile
Sine Wave
« Reply #1 on: February 27, 2012, 03:09:57 pm »
I'm a beginner so i can't specifically say what the issue is but something to keep in mind. Type-casting from a float to an int loses precision. That could be causing a rounding error.

 

anything