Want to Dynamically Change Music in a Ruby CLI App?

Colton Shawn O'Connor
2 min readMar 15, 2021

Hello Friends. I wanted to go back and revisit the first project I made with another friend from the bootcamp, Brett Needham. In this project (find hit here: https://github.com/bigdumbbaby/The_Dungeon) we made an old school text game using active record and some ruby gems. We wanted to incorporate music into the game, setting a unique song depending on the location you are at. So I found some Dungeon Synth to set the mood, seeded each location with a string of the songs file path, and then started working on a way to change the songs.

In order to do this we need to do 3 things:

  1. Get a song to play.
  2. Get a song to stop playing .
  3. Switch to a new song

Get a song to play:

First we just wanted to get a single song to play. To do this we were able to add the following code to our runner file

@pid = spawn( 'afplay', file )

where ‘file’ is the file path of the song you wish to play. And as simple as that we have music! But there is an issue here…the song won’t stop until it plays out. Even if you quit out of the app, the song won’t stop. The songs we were using where droney, dungeon music so they where LONG. This brings us to step 2…

Stop a song that is currently playing:

In order to kill music that is playing, you can run.

pid = fork{ exec 'killall', "afplay"}

And there we go! We can now play a song when we start the app, and kill the song when we quit out. What if we wanna switch songs?

Switch songs:

This gets a little more complicated. If we run the ‘killall’ method, this prevents up from playing a new song, and if we just run the play song method, then we will have two songs playing on top of each other. So to fix this we made two methods…

def switch_songProcess.kill "TERM", @pidend
def play_music(file)@pid = spawn( 'afplay', file )end

This way we can switch songs and then choose the new song. You can call the methods like this

switch_song play_music(*new song path*)

And there you go. Whenever you wanna switch songs, running the ‘switch_song’ method will kill the song that is currently playing, and start a new song that you pass to ‘play_music’.

Final Thoughts:

I hope you found this blog to be helpful in building interesting Active Record CLI applications. I had a lot of fun working on this game. If you would like to see the game in action you can find here: https://github.com/bigdumbbaby/The_Dungeon

--

--