I'm trying to play a local media file using LibVLCSharp and to overlay a metronome sound on top of it. Here's a simplified version of the code I've been using:
private LibVLC libVlc;
private MediaPlayer mediaPlayer;
async Task Open()
{
libVlc = new LibVLC();
Core.Initialize();
Media media = new(libVlc, new Uri(MEDIA_FILE_PATH));
await media.Parse();
mediaPlayer = new MediaPlayer(media);
}
async Task Play()
{
PeriodicTimer metronomeTimer = new(METRONOME_TIMER_INTERVAL);
mediaPlayer.Play();
for (int i = 0; i < 10; i++)
{
PlayMetronomeSound();
await metronomeTimer.WaitForNextTickAsync();
}
}
This code works fine, but there is a small delay between the metronome sound and the media played by LibVLC. If I subscribe to the mediaPlayer.Playing
event, I see that this event is fired about 150 ms after the mediaPlayer.Play()
call. I assume, it's buffering the media during that time?
If that's the case, is there a way to pre-buffer the media in the Open()
method to avoid the delay in Play()
?
The only workaround I was able to find is to call mediaPlayer.Play()
in the Open()
method, then mediaPlayer.Pause()
in the mediaPlayer.Playing
event handler, and then seek to the beginning using mediaPlayer.SeekTo(TimeSpan.Zero)
. In this case, the second call of mediaPlayer.Play()
starts the playback immediately and there are no more synchronization issues, but this feels like a hack to me.
You could try the following custom libvlc option --start-paused
(in libvlc constructor) or :start-paused
as a Media.AddOption
argument. This may produce the result you're after.
Also, why not call PlayMetronomeSound
when the Playing
event fires?