]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blame - helpers/music_file.py
Fix channels and description with blank lines
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / music_file.py
CommitLineData
be27763f
IB
1import threading
2import pydub
3import pygame
4
5class MusicFile:
d479af33 6 def __init__(self, filename, lock, channel_id):
be27763f 7 self.filename = filename
d479af33 8 self.channel_id = channel_id
be27763f
IB
9 self.raw_data = None
10 self.sound = None
11
12 self.loaded = False
23b7e0e5 13 threading.Thread(name = "MSMusicLoad", target = self.load_sound, args = [lock]).start()
be27763f
IB
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
0e5d59f7 24 def is_playing(self):
d479af33 25 return self.channel().get_busy()
0e5d59f7
IB
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
d479af33 39 self.channel().play(self.sound, fade_ms = fade_in * 1000)
be27763f
IB
40
41 def pause(self):
d479af33 42 self.channel().pause()
be27763f 43
0e5d59f7 44 def stop(self, fade_out = 0):
0e5d59f7 45 if fade_out > 0:
d479af33 46 self.channel().fadeout(fade_out * 1000)
0e5d59f7 47 else:
d479af33 48 self.channel().stop()
0e5d59f7
IB
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)
be27763f 56
b86db9f1
IB
57 def wait_end(self):
58 pass
d479af33
IB
59
60 def channel(self):
61 return pygame.mixer.Channel(self.channel_id)