libvlcpython-vlc

How to obtain bitrate, sample rate and bits per sample in python-vlc


I am trying to obtain bitrate, sample rate actual bits per sample of an audio file using python-vlc.

I saw that we can use libvlc_media_tracks_get() to obtain bitrate, but I am not sure how to get the others.

But even if this method can obtain all 3 info, I still can't manage to make the method work. It takes 2 arguments p_md and tracks. I don't understand what is tracks. It says it requires an instance of LP_LP_MediaTrack but I can't somehow find what that means.


Solution

  • Bitrate:

    # This allocates a double pointer and a MediaTrack object in RAM, then points to
    # it, but no value is assigned to this double pointer or the MediaTrack object.
    mediaTrack_pp = ctypes.POINTER(vlc.MediaTrack)()
    
    # Assigns the MediaTrack in the double pointer to the values stored in `media`,
    # returning the amount of media tracks as `n`
    n = vlc.libvlc_media_tracks_get(media, ctypes.byref(mediaTrack_pp))
    
    # Converts the double pointer to `POINTER` class that Python understands. We can
    # then get the value the pointer is pointing at.
    info = ctypes.cast(mediaTrack_pp, ctypes.POINTER(ctypes.POINTER(vlc.MediaTrack) * n))
    
    # This gets the actual value of the double pointer i.e. value of MediaTrack
    media_tracks = info.contents[0].contents
    

    Sample rate (appending the above code):

    # According to the API doc, MediaTrack class has an `u` field which has an
    # `audio` field, containing the audio track.
    audio = ctypes.cast(media_tracks.u.audio, ctypes.POINTER(vlc.AudioTrack))
    
    # The AudioTrack class has a `rate` field, which is the sample rate.
    sample = audio.contents.rate
    

    The main reason I couldn't get the bitrate is because I didn't understand how to get the data type LP_LP_MediaTrack. This is a double pointer of a MediaTrack instance.

    When vlc.libvlc_media_tracks_get(media, ctypes.byref(mediaTrack_pp)) runs, I think the library simply sets copies the MediaTrack instance in media to the actual memory location thatmediaTrack_pp points to

    We can then get the actual object in Python using the ctypes.cast() method. This algorithm should apply on all Python codes that uses LP_xxx data types, even for other libraries.

    With that problem solved, all that left was to crunch the API documentation.
    VLC MediaTrack class documentation