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

Author Topic: loadFromSamples: Parameterize number of samples for dynamic tone duration?  (Read 3024 times)

0 Members and 1 Guest are viewing this topic.

disaux

  • Newbie
  • *
  • Posts: 5
    • View Profile
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?

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

zsbzsb

  • Hero Member
  • *****
  • Posts: 1409
  • Active Maintainer of CSFML/SFML.NET
    • View Profile
    • My little corner...
    • Email
Re: loadFromSamples: Parameterize number of samples for dynamic tone duration?
« Reply #1 on: November 10, 2015, 03:51:15 pm »
Create multiple sound buffers?
Motion / MotionNET - Complete video / audio playback for SFML / SFML.NET

NetEXT - An SFML.NET Extension Library based on Thor

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: loadFromSamples: Parameterize number of samples for dynamic tone duration?
« Reply #2 on: November 10, 2015, 03:52:01 pm »
For arrays with constant size known at runtime, you must use std::vector or std::unique_ptr<sf::Int16[]>.

Don't hesitate to read some good C++ tutorials if you don't know how to use them.
Laurent Gomila - SFML developer