forked from pelegk11/Composer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
music_utils.py
51 lines (40 loc) · 1.34 KB
/
music_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Utils to edit music.
"""
import numpy as np
def find_sample_range(samples):
"""
Find sample range.
:param samples:
:return:
"""
# merge all samples
merged_sample = np.zeros_like(samples[0])
for sample in samples:
merged_sample = np.maximum(merged_sample, sample)
# get all pitches being played
merged_sample = np.amax(merged_sample, axis=0)
# get min and max note
min_note = np.argmax(merged_sample)
max_note = merged_sample.shape[0] - np.argmax(merged_sample[::-1])
return min_note, max_note
def generate_centered_transpose(samples):
"""
Center samples towards the middle of the pitch range.
:param samples:
:return:
"""
num_notes = samples[0].shape[1]
min_note, max_note = find_sample_range(samples)
# find deviation from pitch center
center_deviation = num_notes / 2 - (max_note + min_note) / 2
out_samples = samples
out_lengths = [len(samples), len(samples)]
# center every sample by moving it by center_deviation
for i in range(len(samples)):
out_sample = np.zeros_like(samples[i])
out_sample[:, min_note + int(center_deviation):max_note + int(center_deviation)] = samples[i][:, min_note:max_note]
out_samples.append(out_sample)
return out_samples, out_lengths