BananaMonkey2412
BananaMonkey2412

Reputation: 181

SFML Sound not playing (Operation not permitted)

So I was trying out the SFML tutorial for playing a sound from a local file and came across a weird bug. Whenever I call the playSound function no sound is played and I get an error that I can't find the solution to:

[ALSOFT] (EE) Failed to set real-time priority for thread: Operation not permitted (1)

The strange thing is that if I do the same thing in the main function the sound is played. What is going on here? Here are the only files used in the project, the .wav is just a simple sound file:

main.cpp

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

void playSound() {
    sf::SoundBuffer buffer;
    if (!buffer.loadFromFile("1-retro-arcade-casino-notification.wav"))
        return;
    sf::Sound sound;
    sound.setBuffer(buffer);
    sound.play();
}

int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "Notification test");

    sf::SoundBuffer buffer;
    if (!buffer.loadFromFile("1-retro-arcade-casino-notification.wav"))
        return -1;
    sf::Sound sound;
    sound.setBuffer(buffer);
    sound.play();

    while (window.isOpen()) {
        sf::Event event;

        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                window.close();
            }

            if (event.type == sf::Event::TextEntered) {
                char key = static_cast<char>(event.text.unicode);
                
                if (key == 'p') {
                    playSound();
                }

                if (key == 'q') {
                    window.close();
                }
            }
        }
    }

    return 0;
}

Makefile

all:
    g++ -lsfml-audio -lsfml-graphics -lsfml-window -lsfml-system -o main main.cpp

Upvotes: 0

Views: 1130

Answers (1)

Cortex0101
Cortex0101

Reputation: 927

The sound data is not stored directly in sf::Sound but instead in the sf::SoundBuffer. This class encapsulates the audio data, which is basically an array of 16-bit signed integers (called "audio samples").

Sounds (and music) are played in a separate thread. This means that you are free to do anything you want after calling void play(), except destroying the sound or its data - which you are currently doing.

This is because you have declared your sf::SoundBuffer buffer; inside void playSound(), and subsequently, the sound data gets destroyed as it goes out of scope after returning from void playSound().

To fix your problem, don't declare sf::SoundBuffer in the function. You could just declare it outside the main function, or even pass it as a parameter to playSound().

See the relevant documentation for info.

Upvotes: 4

Related Questions