How to convert loop information between samples and seconds

A place for Ren'Py tutorials and reusable Ren'Py code.
Forum rules
Do not post questions here!

This forum is for example code you want to show other people. Ren'Py questions should be asked in the Ren'Py Questions and Announcements forum.
Post Reply
Message
Author
User avatar
uyjulian
Regular
Posts: 128
Joined: Sun Mar 08, 2015 1:40 pm
Github: uyjulian
Contact:

How to convert loop information between samples and seconds

#1 Post by uyjulian »

Ren'Py has a feature to loop audio files.

The path and loop information can be passed in like the following syntax:

Code: Select all

<loop 1.2345678>path/to/file.ogg
or

Code: Select all

<from 0.1234567 loop 1.2345678>path/to/file.ogg
The argument to "from" and "loop" are specified in seconds.

However, sometimes, you are using a program that will output the loop arguments in samples, such as Loop Tuner 2.

For example, a file with 1.2345678 seconds of audio that has a sample rate of 44100 has 54444 samples.

You will need the sample rate of the file in order to convert between seconds and samples.
In order to get the sample rate of the file, you can use ffprobe (a command line tool included with ffmpeg) to retrieve information:

Code: Select all

$ ffprobe -show_streams path/to/file.ogg
...
sample_rate=44100
...
duration_ts=54444
duration=1.2345678
sample_rate is the sample rate.
duration_ts is the length of the file in samples.
duration is the length of the file in seconds.

You can use an equation to solve for the number of seconds or the number of seconds.
Let s = number of seconds, a = number of samples, r = sample rate.

The equation is the following:
s = a / r

We can solve for the position in seconds:
s = 54444 / 44100
s = 1.2345578231
54444 samples is equal to 1.2345578231 seconds.

We can solve for the position in samples:
1.2345578231 = a / 44100
Multiply both sides by 44100.
54443.99999871 = a
1.2345578231 seconds is equal to 54443.99999871 samples.

Ren'Py will round towards zero internally when converting between samples and seconds, so it is advised to pass in the precise numbers as arguments.

Post Reply

Who is online

Users browsing this forum: No registered users