OffiTracker/drums/wav2drumtxt.py

65 lines
2.2 KiB
Python

import os
import wave
import numpy as np
def save_noise_data(file_path, noise_data):
try:
with open(file_path, 'w') as file:
file.write(str(noise_data.tolist()))
print(f"Noise data saved to {file_path}")
except Exception as e:
print(f"Error saving noise data to {file_path}: {e}")
def extract_noise_data(file_path, duration_ms=100, sample_rate=44100):
try:
with wave.open(file_path, 'rb') as wav_file:
num_channels = wav_file.getnchannels()
sample_width = wav_file.getsampwidth()
frame_rate = wav_file.getframerate()
total_frames = wav_file.getnframes()
if num_channels > 1:
print("Input file must be mono (single channel).")
return
# Adjust for 8-bit audio
if sample_width == 1:
dtype = np.uint8
elif sample_width == 2:
dtype = np.int16
else:
print("Unsupported sample width.")
return
# Use the minimum of specified duration and actual duration of the file
duration_secs = min(duration_ms / 1000.0, total_frames / frame_rate)
num_frames = int(duration_secs * frame_rate)
signal = np.frombuffer(wav_file.readframes(num_frames), dtype=dtype)
# Normalize the signal for 8-bit audio
if sample_width == 1:
signal = (signal - 128) / 128.0
return signal
except Exception as e:
print(f"Error: {e}")
return None
def main():
directory_path = input("Enter the path to the directory containing WAV files (press Enter for current directory): ").strip() or '.'
duration_ms = float(input("Enter the maximum duration in milliseconds: "))
for file_name in os.listdir(directory_path):
if file_name.endswith(".wav"):
input_wave_file = os.path.join(directory_path, file_name)
output_noise_data = extract_noise_data(input_wave_file, duration_ms)
if output_noise_data is not None:
output_file_name = os.path.splitext(file_name)[0] + ".txt"
save_noise_data(output_file_name, output_noise_data)
if __name__ == "__main__":
main()