I want to know how to write audio play callback in python-vlc

423 Views Asked by At

I wrote code to stream audio as simple as the following.

If no callback is registered (part **) this code works fine.

But I would like to register a play callback to preprocess the streamed data.

How to register a callback function can be found by looking at the python-vlc documentation.

But I can't figure out how to write the callback function.

The second argument to the callback function, samples, is a pointer to the data to be played.

How should I write a callback function at the (*) part with this pointer?

Any reply would be appreciated.

import vlc
import re
import requests
import ctypes

url = "http://serpent0.duckdns.org:8088/kbsfm.pls"
res = requests.get(url)
res.raise_for_status()

# retrieve url
p = re.compile("https://.+")
m = p.search(res.text)
url = m.group()

# AudioPlayCb = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_int64)
@vlc.CallbackDecorators.AudioPlayCb
def play_callback(opaque, samples, count, pts):
    """
    @param data: data pointer as passed to L{libvlc_audio_set_callbacks}() [IN].
    @param samples: pointer to a table of audio samples to play back [IN].
    @param count: number of audio samples to play back.
    @param pts: expected play time stamp (see libvlc_delay()).
    """
    
    # HOW DO I RETURN SOMETHING FROM HERE? (*)
    pass
    
    return buffer

instance = vlc.Instance(["--prefetch-buffer-size=2000 --prefetch-read-size=5000 --network-caching=1000"]) #define VLC instance
media = instance.media_new(url)

player = media.player_new_from_media()
player.audio_set_format("f32l", 48000, 2)

# PLAYS WELL WITHOUT THIS LINE (**)
player.audio_set_callbacks(play=play_callback, pause=None, resume=None, flush=None, drain=None, opaque=None)

player.play() #Play the media   

c = input()

I wrote the play callback function as below. I think the buffer_array passed in should be copied to another buffer to play samples.

@vlc.CallbackDecorators.AudioPlayCb
def play_callback(data, samples, count, pts):
    bytes_read = count * 4 * 2
    buffer_array = ctypes.cast(samples, ctypes.POINTER(ctypes.c_char * bytes_read))
    
    # This code is invalid. To do it right, where should buffer_array be copied to? 
    buffer = bytearray(bytes_read)
    buffer[:] = buffer_array.contents
0

There are 0 best solutions below