import os import librosa import numpy as np import soundfile as sf from tqdm import tqdm # Import tqdm for progress tracking from concurrent.futures import ProcessPoolExecutor # Import for parallel processing # Define the directory containing the audio files audio_dir = 'audio' output_dir = 'processed_audio' # Create output directory if it doesn't exist os.makedirs(output_dir, exist_ok=True) # Function to load audio def load_audio(file_path): audio, sr = librosa.load(file_path, sr=None) # Load with original sampling rate return audio, sr # Function to normalize audio def normalize_audio(audio): return audio / np.max(np.abs(audio)) # Function to save audio in a compressed format def save_audio(output_path, audio, sr): # Save the processed audio as MP3 to reduce file size sf.write(output_path.replace('.wav', '.mp3'), audio, sr, format='MP3') # Save as MP3 # Function to process a single audio file def process_audio(file_path): audio, sr = load_audio(file_path) # Load the audio file audio = normalize_audio(audio) # Normalize audio output_path = os.path.join(output_dir, os.path.basename(file_path).replace('.mp3', '.wav')) # Save as .wav save_audio(output_path, audio, sr) # Save the processed audio return os.path.basename(file_path) # Return the filename for logging if __name__ == '__main__': # Protect the main execution # Get a list of all mp3 files in the audio directory audio_files = [os.path.join(audio_dir, filename) for filename in os.listdir(audio_dir) if filename.endswith('.mp3')] # Process audio files in parallel with ProcessPoolExecutor() as executor: for result in tqdm(executor.map(process_audio, audio_files), total=len(audio_files), desc="Processing files", unit="file"): print(f'Processed {result}') # Log the processing