]>
Commit | Line | Data |
---|---|---|
1 | import threading | |
2 | import pydub | |
3 | import pygame | |
4 | ||
5 | class MusicFile: | |
6 | def __init__(self, filename, lock, channel_id, name = None): | |
7 | self.filename = filename | |
8 | self.channel_id = channel_id | |
9 | self.name = name or filename | |
10 | self.raw_data = None | |
11 | self.sound = None | |
12 | ||
13 | self.loaded = False | |
14 | self.flag_paused = False | |
15 | threading.Thread(name = "MSMusicLoad", target = self.load_sound, args = [lock]).start() | |
16 | ||
17 | def load_sound(self, lock): | |
18 | lock.acquire() | |
19 | print("Loading « {} »".format(self.name)) | |
20 | self.raw_data = pydub.AudioSegment.from_file(self.filename).raw_data | |
21 | self.sound = pygame.mixer.Sound(self.raw_data) | |
22 | print("Loaded « {} »".format(self.name)) | |
23 | self.loaded = True | |
24 | lock.release() | |
25 | ||
26 | def is_playing(self): | |
27 | return self.channel().get_busy() | |
28 | ||
29 | def is_paused(self): | |
30 | return self.flag_paused | |
31 | ||
32 | def play(self, fade_in = 0, volume = 100, start_at = 0): | |
33 | self.channel().set_endevent() | |
34 | self.channel().set_endevent(pygame.USEREVENT) | |
35 | self.set_volume(volume) | |
36 | ||
37 | if start_at > 0: | |
38 | song_duration = self.sound.get_length() | |
39 | raw_data_length = len(self.raw_data) | |
40 | start_offset = int((raw_data_length / song_duration) * start_at) | |
41 | start_offset = start_offset - (start_offset % 2) | |
42 | self.sound = pygame.mixer.Sound(self.raw_data[start_offset:]) | |
43 | else: | |
44 | self.sound = pygame.mixer.Sound(self.raw_data) | |
45 | ||
46 | self.channel().play(self.sound, fade_ms = fade_in * 1000) | |
47 | self.flag_paused = False | |
48 | ||
49 | def pause(self): | |
50 | self.channel().pause() | |
51 | self.flag_paused = True | |
52 | ||
53 | def unpause(self): | |
54 | self.channel().unpause() | |
55 | self.flag_paused = False | |
56 | ||
57 | def stop(self, fade_out = 0): | |
58 | if fade_out > 0: | |
59 | self.channel().fadeout(fade_out * 1000) | |
60 | else: | |
61 | self.channel().stop() | |
62 | ||
63 | def set_volume(self, value): | |
64 | if value < 0: | |
65 | value = 0 | |
66 | if value > 100: | |
67 | value = 100 | |
68 | self.sound.set_volume(value / 100) | |
69 | ||
70 | def wait_end(self): | |
71 | pass | |
72 | ||
73 | def channel(self): | |
74 | return pygame.mixer.Channel(self.channel_id) |