SFML community forums

Help => Audio => Topic started by: Babbzzz on January 18, 2015, 05:36:34 am

Title: [SOLVED] No Sound in Terminal
Post by: Babbzzz on January 18, 2015, 05:36:34 am
This is my first program using SFML. I am unable to get any sound output.

#include <SFML/Audio.hpp>

int main()
{
    sf::SoundBuffer buffer;
    if (!buffer.loadFromFile("left.wav"))
        return -1;
    sf::Sound sound;
    sound.setBuffer(buffer);
    sound.play();
    return 0;
}

The program compiles and runs without errors but there is no sound. What seems to be the problem?
Title: Re: No Sound in Terminal
Post by: Jesper Juhl on January 18, 2015, 05:42:35 am
The program terminates just after calling play() so you never have time to hear the sound.
You need an event loop.
Title: Re: No Sound in Terminal
Post by: Babbzzz on January 18, 2015, 06:23:20 am
Thank you. After a little bit of research, I got it working using the below code.

#include <SFML/Audio.hpp>
#include <iostream>

using namespace std;
using namespace sf;

void playSound()
{
    // Load a sound buffer from a wav file
    SoundBuffer Buffer;
    if (!Buffer.loadFromFile("left.wav"))
        cout << "ERROR!" << endl;
    // Create a sound instance and play it
    Sound Sound(Buffer);
    Sound.play();

    // Loop while the sound is playing
    while (Sound.getStatus() == sf::Sound::Playing)
    {
        // Leave some CPU time for other processes
        sf::Time t1 = sf::seconds(0.1f);
        sf::sleep(t1);

        // Display the playing position
        cout << "\rPlaying... " << endl;
    }
}
int main()
{
    playSound();
    cout << "Done" << endl;
    return EXIT_SUCCESS;
}