]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blob - helpers/music_file.py
Fix channels and description with blank lines
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / music_file.py
1 import threading
2 import pydub
3 import pygame
4
5 class MusicFile:
6 def __init__(self, filename, lock, channel_id):
7 self.filename = filename
8 self.channel_id = channel_id
9 self.raw_data = None
10 self.sound = None
11
12 self.loaded = False
13 threading.Thread(name = "MSMusicLoad", target = self.load_sound, args = [lock]).start()
14
15 def load_sound(self, lock):
16 lock.acquire()
17 print("Loading {}".format(self.filename))
18 self.raw_data = pydub.AudioSegment.from_file(self.filename).raw_data
19 self.sound = pygame.mixer.Sound(self.raw_data)
20 print("Loaded {}".format(self.filename))
21 self.loaded = True
22 lock.release()
23
24 def is_playing(self):
25 return self.channel().get_busy()
26
27 def play(self, fade_in = 0, volume = 100, start_at = 0):
28 self.set_volume(volume)
29
30 if start_at > 0:
31 song_duration = self.sound.get_length()
32 raw_data_length = len(self.raw_data)
33 start_offset = int((raw_data_length / song_duration) * start_at)
34 start_offset = start_offset - (start_offset % 2)
35 self.sound = pygame.mixer.Sound(self.raw_data[start_offset:])
36 else:
37 self.sound = pygame.mixer.Sound(self.raw_data)
38
39 self.channel().play(self.sound, fade_ms = fade_in * 1000)
40
41 def pause(self):
42 self.channel().pause()
43
44 def stop(self, fade_out = 0):
45 if fade_out > 0:
46 self.channel().fadeout(fade_out * 1000)
47 else:
48 self.channel().stop()
49
50 def set_volume(self, value):
51 if value < 0:
52 value = 0
53 if value > 100:
54 value = 100
55 self.sound.set_volume(value / 100)
56
57 def wait_end(self):
58 pass
59
60 def channel(self):
61 return pygame.mixer.Channel(self.channel_id)