I'm trying to play sound accompanying a glfw window on mac, in c++. My current approach is to issue a system call (afplay) in a separate thread to play sound, and use "killall afplay" in main thread to stop it when needed.

The current situation is the killall system call is blocking the main thread, and glfw window isn't responding. When press ctrl+c, it says "No matching processes belonging to you were found" and the killall system call returns 256. This ctrl+c exits the system call. When press ctrl+c again, we exit the main thread.

Similar approach works on linux machine.

The afplay and killall command work good when issued directly from terminal.

1, when I call stop_sound() at "position 0", it works (the first binary is playing sound and the sound is killed when the second binary runs), so I think it has something to do with glfw.

2, when I call stop_sound at "position 1", it still blocks.

3, using a new thread to stop the sound or even detaching it does not make a difference

void play_sound(){
    system("afplay my_sound_file.wav");
}
void stop_sound(){
    system("killall afplay");
}
main(){ 

     //position 0 

     while (!glfwWindowShouldClose(window)) {
        if(gui.R_key_pressed() && !play_sound){
            std::thread audio(play_sound);
            audio.detach();
            play_sound = true;
        }

        if(gui.R_key_pressed() && play_sound){
            stop_sound();
            play_sound = false;
        }   
        glfwPollEvents();
    }
    glfwDestroyWindow(window);
    glfwTerminate();

    //position 1

    exit(EXIT_SUCCESS);
}

0 Answers