Код для удаления перекрывающихся нот или объединения очень коротких
- Я написал небольшой код для очищения mid файла, но когда конвертирую в пдф формат для большей читабельности, то на выходе получается грязная нотная тетрадь (для конвертации и проверки я использовал сайт https://melobytes.com/en/app/midi2sheet).
- Мне нужен скрипт, который бы форматировал mid файл в пдф и выравнивал маленький ноты с большими, чтобы файл был читабельный.
- Вот код который у меня есть для очистки дорожки от "пердежа":
- import librosa
import numpy as np
import soundfile as sf
import librosa.display
import matplotlib.pyplot as plt
# Load the audio file
y, sr = librosa.load('/Users/petrivanov/Downloads/separated/htdemucs/testsum41/vocals.wav', sr=None)
# Compute short-time Fourier transform (STFT) to get the magnitude and phase
D = librosa.stft(y)
magnitude, phase = librosa.magphase(D)
# Compute the average magnitude across all frequencies for each frame
avg_magnitude = np.mean(magnitude, axis=0)
# Set a threshold (you might need to adjust this based on your needs)
threshold = 0.02 # example value, may need adjustment
# Identify low-sound frames
low_sound_frames = np.where(avg_magnitude < threshold)
# Silence those frames
magnitude[:, low_sound_frames] = 0
# Reconstruct the audio signal from the modified magnitude and original phase
y_modified = librosa.istft(magnitude * phase)
# Save the modified audio
sf.write('/Users/petrivanov/Downloads/separated/htdemucs/testsum41/vocalsp.wav', y_modified, sr)
# # Optional: Display original and modified audio for comparison
# plt.figure(figsize=(12, 8))
#
# plt.subplot(2, 1, 1)
# librosa.display.waveshow(y, sr=sr)
# plt
- import librosa
Код, который я писал для соединения маленьких нот для получения чистого файла:
from music21 import converter, stream, note
def clean_and_quantize_midi(midi_path, grid_duration):
piece = converter.parse(midi_path)
quantized_stream = stream.Score()
for part in piece.parts:
new_part = stream.Part()
notes_to_remove = []
# Quantize note offsets
for n in part.notes:
n.offset = round(n.offset / grid_duration) * grid_duration
# Sort notes by offset and then duration (descending)
sorted_notes = sorted(part.notes, key=lambda x: (x.offset, -x.duration.quarterLength))
for i in range(len(sorted_notes) - 1):
curr_note = sorted_notes[i]
next_note = sorted_notes[i + 1]
# If two notes start at the same offset, remove the shorter one
if curr_note.offset == next_note.offset:
if curr_note.duration < next_note.duration:
notes_to_remove.append(curr_note)
else:
notes_to_remove.append(next_note)
# Remove notes that have very short durations (e.g., less than a sixteenth note)
if curr_note.duration.quarterLength < 0.125: # Adjust as needed
notes_to_remove.append(curr_note)
# Add only the notes that aren't marked for removal
for n in part.notes:
if n not in notes_to_remove:
new_part.append(n)
quantized_stream.append(new_part)
return quantized_stream
midi_path = "path_to_your_midi_file.mid"
grid_duration = 0.25 # Adjust as needed
cleaned_piece = clean_and_quantize_midi(midi_path, grid_duration)
cleaned_piece.write('midi', 'cleaned_output.mid')