Using the music player

We're now ready to use our music engine. Let's add a couple of new methods to Playlist.

Let's start with a method to get the path of the selection:

    fn selected_path(&self) -> Option<String> {
        let selection = self.treeview.get_selection();
        if let Some((_, iter)) = selection.get_selected() {
            let value = self.model.get_value(&iter, PATH_COLUMN as i32);
            return value.get::<String>();
        }
        None
    }

We start by getting the selection, then we get the iterator for the selection. From the iterator, we can get the value at the specified column to get the path. We can now add a method to load the selected song:

    pub fn play(&self) -> bool {
        if let Some(path) = self.selected_path() {
            self.player.load(&path);
            true
        } else {
            false
        }
    }

If there's a selected song, we load it into the music engine. We return true if a song was loaded.

We'll now use this method in the event handler of the play button:

impl App {
    pub fn connect_toolbar_events(&self) {
        // …

        let playlist = self.playlist.clone();
        let play_image = self.toolbar.play_image.clone();
        let cover = self.cover.clone();
        let state = self.state.clone();
        self.toolbar.play_button.connect_clicked(move |_| {
            if state.lock().unwrap().stopped {
                if playlist.play() {
                    set_image_icon(&play_image, PAUSE_ICON);
                    set_cover(&cover, &playlist);
                }
            } else {
                set_image_icon(&play_image, PLAY_ICON);
            }
        });

        // …
    }
}

We create a copy of the playlist variable because it is moved into the closure. In the latter, we then call the play() method we created just before. We only change the image of the button and show the cover if a song starts to play.

You can now try the music player: open an MP3 file, click play, and you should hear the song. Let's continue to develop the software since many features are missing.