]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blob - helpers/music_file.py
Fix threading problems with ipython
[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):
7 self.filename = filename
8 self.channel = None
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 is not None and 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 = self.sound.play(fade_ms = fade_in * 1000)
40
41 def pause(self):
42 if self.channel is not None:
43 self.channel.pause()
44
45 def stop(self, fade_out = 0):
46 self.channel = None
47 if fade_out > 0:
48 self.sound.fadeout(fade_out * 1000)
49 else:
50 self.sound.stop()
51
52 def set_volume(self, value):
53 if value < 0:
54 value = 0
55 if value > 100:
56 value = 100
57 self.sound.set_volume(value / 100)
58
59 def wait_end(self):
60 pass