c++audioubuntu-16.04sfml

SFML doesn't play any sounds, but no errors


I have a simple c++ programm using SFML to play a .wav sound file. It looks like this:

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


int main()
{
    sf::SoundBuffer buffer;
    if (!buffer.loadFromFile("beep-01a.wav"))
        return -1;

    sf::Sound sound;
    sound.setBuffer(buffer);
    sound.play();
    std::cout << "Hello World" << std::endl;  
    return 0;  
}

I'm running it on ubuntu 16.04 LTS and compiling it with

$ g++ -c main.cpp
$ g++ main.o -o sfml-app -lsfml-audio
$ ./sfml-app 

I've installed SFML with apt-get as a package. When I run the ./sfml-app it outputs "Hello World", but I can't hear anything. I've tried turning the volume up, restarting my computer, putting headphones in, etc. When I play the sound file by double clicking it, it plays a beep sound.

Thanks for your help


Solution

  • There could be many reasons why no sound is played, even if your code was entirely correct.
    However, it isn't, as sf::Sound::play asynchronously plays the sound in another thread (as stated here) but your application finishes pretty fast, thus giving the other thread no real chance to play much of the specified sound buffer.

    So in order to have at least a theoretical chance of hearing anything, I would suggest to insert some instruction to block the main thread, like

    std::cin.get();
    

    right before exiting.