aboutsummaryrefslogtreecommitdiff
path: root/helpers/music_file.py
blob: cdc9836c19a299b82b2ba2fcca17495ea5f53cd9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import threading
import pydub
import pygame

class MusicFile:
    def __init__(self, filename, lock, channel_id, name = None):
        self.filename = filename
        self.channel_id = channel_id
        self.name = name or filename
        self.raw_data = None
        self.sound = None

        self.loaded = False
        self.flag_paused = False
        threading.Thread(name = "MSMusicLoad", target = self.load_sound, args = [lock]).start()

    def load_sound(self, lock):
        lock.acquire()
        print("Loading « {} »".format(self.name))
        self.raw_data = pydub.AudioSegment.from_file(self.filename).set_frame_rate(44100).raw_data
        self.sound = pygame.mixer.Sound(self.raw_data)
        print("Loaded « {} »".format(self.name))
        self.loaded = True
        lock.release()

    def is_playing(self):
        return self.channel().get_busy()

    def is_paused(self):
        return self.flag_paused

    def play(self, fade_in = 0, volume = 100, start_at = 0):
        self.channel().set_endevent()
        self.channel().set_endevent(pygame.USEREVENT)
        self.set_volume(volume)

        if start_at > 0:
            song_duration = self.sound.get_length()
            raw_data_length = len(self.raw_data)
            start_offset = int((raw_data_length / song_duration) * start_at)
            start_offset = start_offset - (start_offset % 2)
            self.sound = pygame.mixer.Sound(self.raw_data[start_offset:])
        else:
            self.sound = pygame.mixer.Sound(self.raw_data)

        self.channel().play(self.sound, fade_ms = fade_in * 1000)
        self.flag_paused = False

    def pause(self):
        self.channel().pause()
        self.flag_paused = True

    def unpause(self):
        self.channel().unpause()
        self.flag_paused = False

    def stop(self, fade_out = 0):
        if fade_out > 0:
            self.channel().fadeout(fade_out * 1000)
        else:
            self.channel().stop()

    def set_volume(self, value):
        if value < 0:
            value = 0
        if value > 100:
            value = 100
        self.sound.set_volume(value / 100)

    def wait_end(self):
        pass

    def channel(self):
        return pygame.mixer.Channel(self.channel_id)