Search code examples
c++clibvlc

libvlc check if media location is valid


I'm using libvlc and I want to check if a media location/path is valid or not:

libvlc_instance_t* inst = libvlc_new(0, NULL);

libvlc_media_t* m = libvlc_media_new_path(inst, "/path/to/nothing");

if (m == NULL)      // Not working
    printf("Err\n");

libvlc_media_player_t* mp = libvlc_media_player_new_from_media(m);

libvlc_media_player_play(mp);

printf("Error: %s\n", libvlc_errmsg()); // (null)

libvlc_media_release(m);
libvlc_media_player_release(mp);
libvlc_release(inst);


return 0;

Libvlc prints some error messages, but I was not able to catch any error in my own code:

Error: (null)
[0x7f8cc0004a58] filesystem access error: cannot open file /path/to/nothing (No such file or directory)
[0x7f8cc0004a58] main access error: File reading failed
[0x7f8cc0004a58] main access error: VLC could not open the file "/path/to/nothing" (No such file or directory).

Solution

  • Sometimes you can't know if there's a problem until you actually try and play the media.

    libvlc_media_player_play() is asynchronous, you can check for errors (or success) by using LibVLC events.

    After you create your media player, get the event manager:

    libvlc_event_manager_t* em =
        libvlc.libvlc_media_player_event_manager(mediaPlayer);
    

    Then register for the event(s) you want:

    libvlc.libvlc_event_attach(
        em, libvlc_MediaPlayerEncounteredError, callback, null);
    

    The callback function is your event handler with type libvlc_callback_t.

    void callback(const struct libvlc_event_t* event, void* userData) {
        if (event->type == libvlc_MediaPlayerEncounteredError) {
            // ...etc...
        }
    }