Skip to content

Best Practices

Hangman edited this page Jul 5, 2023 · 9 revisions

Streaming ogg and duration measurement

When using StreamedSoundSource to stream an ogg, you may have run into the problem that the duration is not available.
The good news is, we can fix it. wav, flac, mp3 and aiff don't suffer from this issue by the way.

Why does this happen?

It is in the nature of a data stream that we do not know how long it is until it's fully processed. Obviously, processing it completely isn't an option. To our advantage, the Vorbis decoder has a solution for this, but it must be able to seek the stream to do so. A normal InputStream as it is provided by FileHandle.read() isn't seekable.

Solution

Instead we need a FileHandle.file(), which is only valid when using Gdx.files.absolute() and Gdx.files.external(). Files identified by those FileTypes on the other hand are only valid when not packed into a jar. Unfortunately, packing all assets into the jar is libGDX's standard behavior when running the desktop:dist gradle task.
First step to fix the issue: Change all your ogg paths to use Gdx.files.absolute.

StreamedSoundSource source = new StreamedSoundSource(Gdx.files.absolute("myOgg.ogg"));

Second step: Exclude all assets or at least the ogg files from being packed. Add this to the desktop:dist task (or jar task when using gdx-liftoff):

from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } } 
    processResources.exclude('*')
// this will exclude all assets but you can change it to only exclude ogg files if you rather want to limit it to those