Ask coding questions

← Back to all posts
How to force audio playing in a thread to stop?
Typhlotion (1)

After a ridiculous amount of fiddling with the question, i've gotten audio to work on replit. The only thing that's stopping me from implementing audio into a project that i'm working on (specifically for C++) is that I don't know how to force audio to stop playing. The project which i'm trying to implement audio into is a text based game, and i'm trying to get audio to play on the background of some fights using multithreading. My problem is, once I join the audio thread with the thread for gameplay, I can't make the audio stop playing once the gameplay is done. Can anyone lend a hand?
I should point out that i've got very little knowledge on threading, and even less on python, which i'm using to run the audio.

Comments
hotnewtop
btfuss (177)

This is a helpful resource: https://stackoverflow.com/questions/56571886/how-to-force-stop-sound-bgm-being-played-through-playsound-method
Maybe this: http://www.cplusplus.com/forum/beginner/251019/
Also this: https://stackoverflow.com/questions/64712572/play-pause-stop-mp3-audio-file-visual-c

Hope these helped!

Also you could have a constant while loop in the thread to check if a variable says turn off sound in a thread, which would stop the sound!

Typhlotion (1)

@btfuss I tried having a constant while loop in the thread to turn off the sound, but that doesn't work (it just kind of crashes) and the sound file keeps playing. I think that because I'm telling the C++ code to run python code that then runs audio, the python code itself doesn't stop. I know how to get the python code started from C++, but is there any way to force it to stop?
I probably should've been more specific in my original post, that's my bad. Still, is there any way for me to tell the python code to stop running from C++?

btfuss (177)

@Typhlotion

pkill -f file.py

Can be run in bash. I think in cpp you can run bash:

#include <stdlib.h>
int main() {
  system("pkill -f file.py");
}

Here is a resource: https://stackoverflow.com/questions/40652793/how-to-kill-python-script-with-bash-script

Typhlotion (1)

@btfuss I also tried this method, but the music didn't stop playing and all I got was an error that said:
terminate called without an active exception
at the end of my code.

btfuss (177)

@Typhlotion Ok thats weird. Better idea: In the python file, make your music into a thread. Have another thread constantly checking if a bash enviornment variable changes, and if it does than stop the music thread.