I have a function that plays a sound that I want to continue executing after my main
program prints to standard output and exits. My reasoning is that I want the sound to finish playing after the program has exited but I don't want the main
program to wait for the sound to finish playing before it exits.
I found a method for executing the sound in an independent process by turning it into an executable named playsound
and doing go install
. Then in my main program, I call this at the end of main()
:
func startPlaySound() {
cmd := exec.Command("playsound")
cmd.Start()
}
main() {
// code that prints and exits
startPlaySound()
}
This works but I would like to be able to play the sound after the main program exits without creating an executable file. I would rather run the equivalent of cmd.Start()
on the function containing the code to play the sound.
In other words, I would like it to look something like this:
func playSound() {
// code that plays the sound
}
func startPlaySound() {
cmd := CmdFromFunction(playSound)
cmd.Start()
}
main() {
// code that prints and exits
startPlaySound()
}
Does something like CmdFromFunction
exist?
Response to Question Feedback
- This is not a duplicate of How do I fork a go process?. I am not trying to fork the
main
goroutine. I am trying to detachplaySound
into a separate process that will continue executing after themain
goroutine exits. Both of the answers to that question involve executing an external program, which is exactly what I am trying to avoid. - "go routines are not meant to be processes" - I literally turned the code from
playSound
into an executable calledplaysound
and am now executing it as a process usingcmd.Start()
. I'm just trying to find a more direct route for doing that than creating an entirely separate executable file.