Search code examples
rubylibgosu

How to pause music tracks without skipping them


I am working on a GUI music player, and my program needs to play all the tracks in order. I also need to pause the tracks when I press the right arrow key:

def button_down(id)
  case id
  when Gosu::MsLeft
    @locs = [mouse_x, mouse_y]
      if area_clicked(mouse_x, mouse_y)
      @show_tracks = true
      @track_index = 0
      @track_location = @albums[3].tracks[@track_index].location.chomp
      playTrack(@track_location, @track_index)
    end 
  when Gosu::KbRight 
    @song.pause()
  when Gosu::KbLeft 
    @song.play()
  end 
end

I hit a wall since my update method does this:

def update
  if (@song != nil)
    count = @albums[3].tracks.length
    track_index = @track_index + 1
    if (@song.playing? == false && track_index < count) 
      track_location = @albums[3].tracks[track_index].location.chomp
      playTrack(track_location, track_index)
    end
  end 
end

It checks if the song is playing and if it is false, it moves onto the next track. My pause button is essentially a skip-track button due to this. I need if (@song.playing? == false) to play the second track when the first track ends.

This is the playTrack method:

def playTrack(track_location, track_index)
  @song = Gosu::Song.new(track_location)
  @track_name = @albums[3].tracks[track_index].name.to_s
  @album_name = @albums[3].title.to_s
  @song.play(false)
  @track_index = track_index
end

Solution

  • @song.playing? will be false if the song is either paused or stopped, so you cannot distinguish those states that way.

    Fortunately, there's also Song#paused?:

    Returns true if this song is the current song and playback is paused.

    Code-wise you'd write something like this:

    if @song.paused?
      @song.play
    elsif [email protected]? && track_index < count
      # just like before
    end