cheofusi / just_playback

A small library for playing audio files in python, with essential playback functionality.
MIT License
64 stars 7 forks source link

Fade at the End #24

Open PyFlat-JR opened 1 year ago

PyFlat-JR commented 1 year ago

Is there a way to fade the music out at the end of the file like in Pygame Mixer. And if there's no way is it possible for you to code it? Otherwise i can try on my own, but i think it would be faster if you do it.

Btw i'm a big fan of this module, i searched for sth like this for like 2 days and then i found this.

Thanks in advance, Johannes

PrajwalVandana commented 1 year ago

I'm not a contributor, but the feature you requested is not built in, as far as I know. You could try something like this:

import threading
import time

from just_playback import Playback

class PlaybackFadeable(Playback):
    def _fade(self, start_fade, init_vol, dest_vol):
        self.set_volume(init_vol)
        while True:
            if not self.active:
                break

            secs_remaining = self.duration - self.curr_pos
            if secs_remaining < start_fade:
                self.set_volume(  # simple linear fade
                    (init_vol - dest_vol) * secs_remaining / start_fade
                    + dest_vol
                )
                time.sleep(0.1)  # might not need this, IDK
        self.set_volume(init_vol)

    def play(self, start_fade=2, init_vol=1, dest_vol=0):
        super().play()
        p = threading.Thread(
            target=self._fade,
            args=(start_fade, init_vol, dest_vol),
            daemon=True,
        )
        p.start()

playback = PlaybackFadeable()
playback.load_file("some audio file.wav")
playback.play(start_fade=2, init_vol=1, dest_vol=0)  # fade from full volume to silence, starting 2 seconds before the end
PyFlat-JR commented 1 year ago

This helps me a lot, thank you. I had the same idea but didn't deal with the module enough.

cheofusi commented 1 year ago

Hi everyone,

Support for fading in/out would be great to have in the next release.

Any ideas on how the API could look like ??

PrajwalVandana commented 1 year ago

How about having them as (probably keyword-only) arguments in the load_file method? Another option would be to have two new methods, set_fade_in and set_fade_out ... but it would have to be made clear that calling either method would not affect already playing audio (i.e. previous calls to play).