In C++ audio context, can you please provide an implementation for a sinusoidal generator?
- User
In C++ audio context, can you please provide an implementation for a sinusoidal generator?
- Assistant
In C++ audio context, can you please provide an implementation for a sinusoidal generator?
Certainly! Below is an implementation of a simple sinusoidal audio generator in C++. This example uses basic C++ features, but keep in mind that actual audio integration may require additional libraries such as PortAudio, RtAudio, or others, depending on your platform and requirements.
Here is a simple implementation that generates a sinusoidal waveform and outputs it to the console. For a real audio application, you would typically output to audio hardware.
#include <iostream>
#include <cmath>
#include <vector>
class SinusoidalGenerator {
public:
SinusoidalGenerator(double sampleRate, double frequency)
: sampleRate(sampleRate), frequency(frequency), currentSample(0) {}
// Generate the next sample
double nextSample() {
double sample = amplitude * sin(2.0 * M_PI * frequency * (currentSample / sampleRate));
currentSample++;
return sample;
}
void setAmplitude(double amp) {
amplitude = amp;
}
private:
double sampleRate; // Sample rate in Hz
double frequency; // Frequency of the sine wave in Hz
double amplitude = 1.0; // Amplitude of the wave
long currentSample; // Current sample position
};
int main() {
const double sampleRate = 44100.0; // 44.1 kHz sample rate
const double frequency = 440.0; // Frequency of A4
const int numSamples = 44100; // Number of samples to generate (1 second)
SinusoidalGenerator generator(sampleRate, frequency);
std::vector<double> samples;
// Generate the samples
for (int i = 0; i < numSamples; ++i) {
samples.push_back(generator.nextSample());
}
// Output the samples (just for demonstration, replace with real audio output)
for (const auto& sample : samples) {
std::cout << sample << std::endl; // For demonstration purposes
}
return 0;
}
Class SinusoidalGenerator:
main() function:
SinusoidalGenerator for a frequency of 440 Hz (the musical note A4).The output method used here is just to demonstrate the generated samples in the console, which won't produce audible sound. To hear the generated audio, you'll typically need to use an audio library that allows you to play the samples through your PC's sound system.
If you want to integrate this with real audio output, consider using libraries such as:
Using one of these libraries would involve creating a callback function that generates audio on-the-fly, rather than outputting samples to the console.
Not yet included in a published release.