Untitled

Anonymous
python
10/03/2026 1:23 PM
2.0 KB
2
Indexable
import wave
import numpy as np
import matplotlib.pyplot as plt

def read_and_normalize_audio(file_path):
    """Reads a .wav file and returns the normalized signal, sample rate, and time axis."""
    with wave.open(file_path, 'rb') as wav_file:
        sample_rate = wav_file.getframerate()
        num_samples = wav_file.getnframes()
        raw_data = wav_file.readframes(num_samples)
        
    # Convert raw binary bytes to 16-bit integers
    signal = np.frombuffer(raw_data, dtype=np.int16)
    
    # Normalize the amplitude to a standard [-1.0, 1.0] range
    max_amp = np.max(np.abs(signal))
    if max_amp > 0:
        signal_normalized = signal / max_amp
    else:
        signal_normalized = signal
        
    # Generate the X-axis (time in seconds)
    duration = num_samples / sample_rate
    time_axis = np.linspace(0, duration, num=num_samples)
    
    return signal_normalized, sample_rate, time_axis

def plot_single_waveform(file_path):
    """Plots the generated signal against its time axis."""
    signal, sample_rate, time_axis = read_and_normalize_audio(file_path)
    
    plt.figure(figsize=(10, 3))
    plt.plot(time_axis, signal, color='darkgray', linewidth=0.5)
    
    plt.title(f'Waveform: {file_path}')
    plt.xlabel('Time (s)')
    plt.ylabel('Amplitude')
    plt.ylim(-1.1, 1.1) 
    
    plt.tight_layout()
    plt.show()

# Replace with the name of one of your test files to test the output
if __name__ == "__main__":
    plot_single_waveform("studio_M2.wav")
Editor is loading...
Leave a Comment