]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blob - helpers/music_file.py
Put time duration in playlist
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / music_file.py
1 import threading
2 import pydub
3 import pygame
4 import math
5 import time
6
7 class MusicFile:
8 def __init__(self, filename, lock, channel_id, name = None, gain = 1):
9 self.filename = filename
10 self.channel_id = channel_id
11 self.name = name or filename
12 self.raw_data = None
13 self.gain = gain
14
15 self.loaded = False
16 self.flag_paused = False
17 threading.Thread(name = "MSMusicLoad", target = self.load_sound, args = [lock]).start()
18
19 def load_sound(self, lock):
20 lock.acquire()
21 print("Loading « {} »".format(self.name))
22 volume_factor = 20 * math.log10(self.gain)
23 audio_segment = pydub.AudioSegment.from_file(self.filename).set_frame_rate(44100).apply_gain(volume_factor)
24 self.sound_duration = audio_segment.duration_seconds
25 self.raw_data = audio_segment.raw_data
26 print("Loaded « {} »".format(self.name))
27 self.loaded = True
28 lock.release()
29
30 def is_playing(self):
31 return self.channel().get_busy()
32
33 def is_paused(self):
34 return self.flag_paused
35
36 @property
37 def sound_position(self):
38 if self.is_playing() and not self.is_paused():
39 return min(time.time() - self.started_at, self.sound_duration)
40 elif self.is_playing() and self.is_paused():
41 return min(self.paused_at - self.started_at, self.sound_duration)
42 else:
43 return 0
44
45 def play(self, fade_in = 0, volume = 100, start_at = 0):
46 self.channel().set_endevent()
47 self.channel().set_endevent(pygame.USEREVENT)
48 self.set_volume(volume)
49
50 if start_at > 0:
51 raw_data_length = len(self.raw_data)
52 start_offset = int((raw_data_length / self.sound_duration) * start_at)
53 start_offset = start_offset - (start_offset % 2)
54 sound = pygame.mixer.Sound(self.raw_data[start_offset:])
55 else:
56 sound = pygame.mixer.Sound(self.raw_data)
57
58 self.started_at = time.time()
59 self.channel().play(sound, fade_ms = int(fade_in * 1000))
60 self.flag_paused = False
61
62 def pause(self):
63 self.paused_at = time.time()
64 self.channel().pause()
65 self.flag_paused = True
66
67 def unpause(self):
68 self.started_at += (time.time() - self.paused_at)
69 self.channel().unpause()
70 self.flag_paused = False
71
72 def stop(self, fade_out = 0):
73 if fade_out > 0:
74 self.channel().fadeout(int(fade_out * 1000))
75 else:
76 self.channel().stop()
77
78 def set_volume(self, value):
79 if value < 0:
80 value = 0
81 if value > 100:
82 value = 100
83 self.channel().set_volume(value / 100)
84
85 def wait_end(self):
86 pass
87
88 def channel(self):
89 return pygame.mixer.Channel(self.channel_id)