]>
git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blob - music_file.py
9acdedf45026b014e39390aac7ef37a83734aa8d
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
16 self
.flag_paused
= False
17 threading
.Thread(name
= "MSMusicLoad", target
= self
.load_sound
, args
= [lock
]).start()
19 def load_sound(self
, lock
):
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
))
31 return self
.channel().get_busy()
34 return self
.flag_paused
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
)
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
)
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
:])
56 sound
= pygame
.mixer
.Sound(self
.raw_data
)
58 self
.started_at
= time
.time()
59 self
.channel().play(sound
, fade_ms
= int(fade_in
* 1000))
60 self
.flag_paused
= False
63 self
.paused_at
= time
.time()
64 self
.channel().pause()
65 self
.flag_paused
= True
68 self
.started_at
+= (time
.time() - self
.paused_at
)
69 self
.channel().unpause()
70 self
.flag_paused
= False
72 def stop(self
, fade_out
= 0):
74 self
.channel().fadeout(int(fade_out
* 1000))
78 def set_volume(self
, value
):
83 self
.channel().set_volume(value
/ 100)
89 return pygame
.mixer
.Channel(self
.channel_id
)