1
Audio / loadFromSamples: Parameterize number of samples for dynamic tone duration?
« on: November 10, 2015, 03:25:00 pm »
Hello community,
I am generating a beep tone which lasts 1 second due to my specification of SAMPLES=44100. I know that I would have to set it to 44100 to get two seconds duration. However, I need to generate tones of different length so it would be useful if I could hand over the length as a parameter.
Unfortunately, SoundBuffer::loadFromSamples() needs as first paramter an const int16 array of size SAMPLES. Thus, SAMPLE is const as well and can not be altered dynamically.
Is there a way to achieve what I am trying to do?
based on https://github.com/SFML/SFML/wiki/Tutorial:-Play-Sine-Wave
Cheers,
Dietmar
I am generating a beep tone which lasts 1 second due to my specification of SAMPLES=44100. I know that I would have to set it to 44100 to get two seconds duration. However, I need to generate tones of different length so it would be useful if I could hand over the length as a parameter.
Unfortunately, SoundBuffer::loadFromSamples() needs as first paramter an const int16 array of size SAMPLES. Thus, SAMPLE is const as well and can not be altered dynamically.
Is there a way to achieve what I am trying to do?
Quote
int main() {
playSound(2); // should result in 88200 samples (2 seconds playback time)
... much code that takes ages
return 0;
}
Quote
void playSound(int duration)
{
const unsigned SAMPLES = 44100 * duration; // fail
const unsigned SAMPLE_RATE = 44100;
const unsigned AMPLITUDE = 30000;
sf::Int16 raw[SAMPLES];
const double TWO_PI = 6.28318;
const double increment = 440./44100;
double x = 0;
for (unsigned i = 0; i < SAMPLES; i++) {
raw = AMPLITUDE * sin(x*TWO_PI);
x += increment;
}
sf::SoundBuffer Buffer;
if (!Buffer.loadFromSamples(raw, SAMPLES, 1, SAMPLE_RATE)) {
std::cerr << "Loading failed!" << std::endl;
return 1;
}
sf::Sound Sound;
Sound.setBuffer(Buffer);
Sound.play();
}
based on https://github.com/SFML/SFML/wiki/Tutorial:-Play-Sine-Wave
Cheers,
Dietmar