Search code examples
c++sfml

SFML Audio not playing


I have this code:

#include <SFML/Audio.hpp>
#include <unistd.h>
#include <cmath>

int main()
{
    const double volume = 10000;
    const sf::Uint64 sampleCount = 44100;
    sf::Int16* samples = new sf::Int16[sampleCount];
    for (sf::Uint64 i = 0; i < sampleCount; i++) {
        samples[sampleCount] = sin(((double)i / 44100.0)*M_PI*2.0*440) * volume;
    }

    sf::SoundBuffer b;
    b.loadFromSamples(samples, sampleCount, 1, 44100);

    sf::Sound s;
    s.setBuffer(b);
    s.play();

    usleep(1000000);

    delete [] samples;

    return 0;
}

And I compile with:

g++ -o sound main.cpp -framework SFML -framework sfml-audio -F/Library/Frameworks

It should play a sine wave at 440 Hz for 1 second, but it doesn't play anything, and just waits for one second.


Solution

  • Your loop invokes undefined behavior by writing to memory you don't own, specifically samples[sampleCount]. My best guess is that it plays either all zeroes or random static, but it's up to your compiler to figure out how exactly it fails.

    This:

    sf::Int16* samples = new sf::Int16[sampleCount];
    for (sf::Uint64 i = 0; i < sampleCount; i++) {
        samples[sampleCount] = sin(((double)i / 44100.0)*M_PI*2.0*440) * volume;
    }
    

    needs to be

    sf::Int16* samples = new sf::Int16[sampleCount];
    for (sf::Uint64 i = 0; i < sampleCount; i++) {
        samples[i] = sin(((double)i / 44100.0)*M_PI*2.0*440) * volume;
    }