Make an advanced python script that enhances an audio file vocals by enhancing the…
- User
Make an advanced python script that enhances an audio file vocals by enhancing the background noise and improving the overall quality of the vocal.
- Assistant
Make an advanced python script that enhances an audio file vocals by enhancing the background noise and improving the overall quality of the vocal.
Enhancing vocals in an audio file involves multiple steps, including noise reduction, equalization, compression, and possibly source separation to isolate the vocals from the background. Below is an advanced Python script that performs these tasks using several powerful libraries:
Before running the script, ensure you have Python 3.7 or higher installed. You will also need to install the following Python libraries:
pip install spleeter noisereduce librosa pydub scipy soundfile numpy matplotlib
Additionally, FFmpeg is required by Pydub for handling various audio formats. You can download it from FFmpeg's official website and ensure it's added to your system's PATH.
import os
import sys
import argparse
import numpy as np
import librosa
import soundfile as sf
from spleeter.separator import Separator
import noisereduce as nr
from pydub import AudioSegment
from scipy.signal import butter, lfilter
def separate_vocals(input_path, output_dir):
"""
Separates vocals from background using Spleeter.
"""
print("Separating vocals and accompaniment...")
separator = Separator('spleeter:2stems') # 2 stems: vocals and accompaniment
separator.separate_to_file(input_path, output_dir)
vocals_path = os.path.join(output_dir, os.path.splitext(os.path.basename(input_path))[0], 'vocals.wav')
accompaniment_path = os.path.join(output_dir, os.path.splitext(os.path.basename(input_path))[0], 'accompaniment.wav')
return vocals_path, accompaniment_path
def reduce_noise(vocals_path, reduced_noise_path):
"""
Reduces noise in the vocals using noisereduce.
"""
print("Reducing noise in vocals...")
y, sr = librosa.load(vocals_path, sr=None)
# Estimate noise from the first 0.5 seconds
noise_sample = y[:int(0.5 * sr)]
y_reduced = nr.reduce_noise(y=y, sr=sr, y_noise=noise_sample, prop_decrease=1.0)
sf.write(reduced_noise_path, y_reduced, sr)
return reduced_noise_path
def apply_eq(y, sr):
"""
Applies a simple equalization to enhance vocal frequencies.
Boosts frequencies around 3 kHz to add presence.
"""
print("Applying equalization...")
# Design a peak filter to boost around 3 kHz
center_freq = 3000 # 3 kHz
Q = 1.0 # Quality factor
gain_db = 5.0 # Gain in dB
# Convert to radians
w0 = center_freq / (sr / 2)
b, a = librosa.filters.peak_eq(w0, Q, gain_db)
y_eq = lfilter(b, a, y)
return y_eq
def apply_compression(y, sr, threshold=0.1, ratio=4.0, attack=0.01, release=0.1):
"""
Applies dynamic range compression to the audio.
"""
print("Applying compression...")
# Simple compressor implementation
envelope = np.abs(y)
attack_samples = int(attack * sr)
release_samples = int(release * sr)
gain = np.ones_like(y)
for i in range(1, len(y)):
if envelope[i] > threshold:
target = 1 - (1 / ratio)
else:
target = 1
if target < gain[i-1]:
gain[i] = max(target, gain[i-1] - (1.0 / attack_samples))
else:
gain[i] = min(target, gain[i-1] + (1.0 / release_samples))
y_compressed = y * gain
return y_compressed
def normalize_audio(y, target_dBFS=-20.0):
"""
Normalizes the audio to a target dBFS.
"""
print("Normalizing audio...")
rms = np.sqrt(np.mean(y**2))
target_rms = 10**(target_dBFS / 20)
y_normalized = y * (target_rms / rms)
return y_normalized
def enhance_vocals(vocals_path, enhanced_path):
"""
Enhances the vocals by applying noise reduction, equalization, compression, and normalization.
"""
# Step 1: Reduce Noise
reduced_noise_path = "reduced_noise_vocals.wav"
reduce_noise(vocals_path, reduced_noise_path)
# Step 2: Load the noise-reduced audio
y, sr = librosa.load(reduced_noise_path, sr=None)
# Step 3: Apply Equalization
y_eq = apply_eq(y, sr)
# Step 4: Apply Compression
y_compressed = apply_compression(y_eq, sr)
# Step 5: Normalize
y_normalized = normalize_audio(y_compressed)
# Save the enhanced vocals
sf.write(enhanced_path, y_normalized, sr)
print(f"Enhanced vocals saved to {enhanced_path}")
def merge_audio(enhanced_vocals_path, accompaniment_path, output_path):
"""
Merges the enhanced vocals with the accompaniment.
"""
print("Merging enhanced vocals with accompaniment...")
# Load enhanced vocals and accompaniment
vocals = AudioSegment.from_file(enhanced_vocals_path)
accompaniment = AudioSegment.from_file(accompaniment_path)
# Ensure both tracks have the same duration
if len(vocals) > len(accompaniment):
accompaniment = accompaniment.overlay(vocals, position=0)
else:
vocals = vocals.overlay(accompaniment, position=0)
# Combine the two
combined = accompaniment + vocals # Adjust volume if necessary
# Export the combined audio
combined.export(output_path, format="wav")
print(f"Final enhanced audio saved to {output_path}")
def main(input_file, output_dir, output_file):
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Step 1: Separate vocals and accompaniment
vocals_path, accompaniment_path = separate_vocals(input_file, output_dir)
# Step 2: Enhance vocals
enhanced_vocals_path = os.path.join(output_dir, "enhanced_vocals.wav")
enhance_vocals(vocals_path, enhanced_vocals_path)
# Step 3: Merge enhanced vocals with accompaniment
merge_audio(enhanced_vocals_path, accompaniment_path, output_file)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Enhance vocals in an audio file.")
parser.add_argument("input_file", type=str, help="Path to the input audio file.")
parser.add_argument("-o", "--output_dir", type=str, default="output", help="Directory to save intermediate and output files.")
parser.add_argument("-out", "--output_file", type=str, default="output/enhanced_audio.wav", help="Path for the final enhanced audio file.")
args = parser.parse_args()
main(args.input_file, args.output_dir, args.output_file)
Source Separation with Spleeter:
Noise Reduction with Noisereduce:
Equalization:
center_freq, Q, and gain_db parameters to suit your needs.Compression:
threshold, ratio, attack, and release can be tweaked for different vocal characteristics.Normalization:
-20 dBFS by default).Merging:
Save the Script:
enhance_vocals.py.Prepare Your Audio File:
Run the Script:
python enhance_vocals.py path_to_input_audio -o path_to_output_directory -out path_to_final_output.wav
python enhance_vocals.py song.mp3 -o enhanced_output -out enhanced_song.wav
Result:
enhanced_output directory containing intermediate files and the final enhanced_song.wav with improved vocals.Performance:
Quality Tweaks:
Audio Formats:
Error Handling:
Extensions:
This advanced Python script provides a comprehensive approach to enhancing vocals in an audio file by isolating the vocals, reducing noise, applying equalization and compression, and finally merging the enhanced vocals back with the accompaniment. Depending on your specific needs, you can further customize and extend the script to achieve the desired audio quality.
Not yet included in a published release.