1

I have a audio file namely audio.wav. I want to mute the peaks of the audio file if the amplitudes of those peaks are greater than 0.2

Although I am able to mark them successfully, I am unable to mute them (i.e, setting the amplitude as 0). What am I doing wrong? Here's my code.

import scipy.signal as signal
import numpy as np
import matplotlib.pyplot as plt
import soundfile as sf

# Load the audio file
audio_file = '/content/audio.wav'
y, sr = sf.read(audio_file)

# Extract one of the channels (assuming they contain the same information)
y_mono = y[:, 0]

# Find the indices of the peaks where amplitude is greater than 0.2
peaks, _ = signal.find_peaks(y_mono, height=0.2)

# Visualize the audio waveform with peaks marked by red crosses
plt.figure(figsize=(14, 5))
plt.plot(y_mono)
plt.plot(peaks, y_mono[peaks], "x", color="red")
plt.title("Audio with Peaks Marked")
plt.xlabel("Sample")
plt.ylabel("Amplitude")
plt.show()

# Make a copy of the audio data
y_muted = np.copy(y_mono)

# Set the amplitude of the peak samples to 0 in the copy
y_muted[peaks] = 0

# Visualize the muted audio waveform
plt.figure(figsize=(14, 5))
plt.plot(y_muted)
plt.title("Muted Audio")
plt.xlabel("Sample")
plt.ylabel("Amplitude")
plt.show()

# Export the muted audio to a new file
muted_file = '/content/muted_audio.wav'
sf.write(muted_file, np.column_stack((y_muted, y[:, 1])), sr)

Audio with peaks marked:

Audio with peaks marked

But when it comes to muted audio, the peaks are still present in the output:

Output

How to set the amplitude of those marked peaks to 0 and plot them accordingly.

  • Since this is missing sample data, it's not a complete [mre], and is therefore less likely to get an answer. Always include a complete [mre]. From the [documentation](https://upload.wikimedia.org/wikipedia/commons/6/61/DescenteInfinie.ogg), `url = "https://upload.wikimedia.org/wikipedia/commons/6/61/DescenteInfinie.ogg"` and `data, samplerate = sf.read(io.BytesIO(urlopen(url).read()))` would work. Update your question appropriately with sample data or a sample file that will be available in perpetuity. – Trenton McKinney Apr 16 '23 at 20:27
  • 1
    I tried your code with a sinusoidal signal. You are removing the peaks, not all the signal around the peaks. https://i.imgur.com/Wc5US0T.png – Guimoute Apr 16 '23 at 21:20
  • you can do `y_muted[(y_muted >= 0.2) | (y_muted <= -0.2)] = 0` if you also want the negative peaks, otherwise `y_muted[y_muted >= 0.2] = 0`, which results in [this plot](https://i.stack.imgur.com/sOZzb.png) & [code and plot](https://i.stack.imgur.com/U4Tgr.png) – Trenton McKinney Apr 16 '23 at 22:11

0 Answers0