AUDIO RECORDING & PLAYBACK APPS: 10 REAL-TIME VOICE PROCESSING EXAMPLES

Build audio recording, voice modulation, speech analysis, and sound playback applications in Gradio using the versatile gr.Audio component.

⚡ Handling Sound in Gradio (`gr.Audio`)

The gr.Audio component allows users to record their voice directly via microphone or upload pre-recorded audio files (WAV, MP3, FLAC). Gradio passes audio data into Python functions as either a file path or a NumPy array tuple (sample_rate, data), enabling powerful audio manipulation pipelines.

Example 1: Microphone Voice Recorder & Instant Playback
Records live microphone audio and renders it immediately in a playable audio output player.
Python (audio_ex1.py)
import gradio as gr

def echo_audio(audio_file):
    return audio_file

demo = gr.Interface(
    fn=echo_audio,
    inputs=gr.Audio(sources=["microphone", "upload"], label="Record or Upload Audio"),
    outputs=gr.Audio(label="Playback Stream"),
    title="Instant Voice Recorder & Player"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Instant Voice Recorder & Player

🎙️ Microphone Recorder Box
▶️ Audio Playback Player
Example 2: Audio Time Reversal Effect
Reverses the audio waveform array to play speech backwards using NumPy slicing.
Python (audio_ex2.py)
import gradio as gr
import numpy as np

def reverse_audio(audio):
    if audio is None:
        return None
    sr, y = audio
    # Reverse audio data array
    return sr, y[::-1]

demo = gr.Interface(
    fn=reverse_audio,
    inputs=gr.Audio(type="numpy", label="Input Speech"),
    outputs=gr.Audio(type="numpy", label="Reversed Speech"),
    title="Backward Audio Effect Studio"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Backward Audio Effect Studio

Input Speech Player
Reversed Speech Player (Backward Playback)
Example 3: Audio Metadata Inspector & Duration Calculator
Calculates audio sample rate, total frame count, and duration in seconds from NumPy arrays.
Python (audio_ex3.py)
import gradio as gr

def inspect_audio(audio):
    if audio is None:
        return "No audio provided."
    sr, y = audio
    duration = len(y) / sr
    return f"Sample Rate: {sr} Hz | Total Frames: {len(y):,} | Duration: {duration:.2f} seconds"

demo = gr.Interface(
    fn=inspect_audio,
    inputs=gr.Audio(type="numpy", label="Upload Audio File"),
    outputs=gr.Textbox(label="Audio Metadata"),
    title="Audio Properties Inspector"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Audio Properties Inspector

Upload Audio File Player
Sample Rate: 44100 Hz | Total Frames: 132,300 | Duration: 3.00 seconds
Example 4: Volume Boost & Amplitude Amplifier
Amplifies audio signal volume by multiplying the sample amplitude array by a gain factor.
Python (audio_ex4.py)
import gradio as gr
import numpy as np

def amplify_audio(audio, gain):
    if audio is None:
        return None
    sr, y = audio
    amplified = np.clip(y * gain, -32768, 32767).astype(np.int16)
    return sr, amplified

demo = gr.Interface(
    fn=amplify_audio,
    inputs=[gr.Audio(type="numpy", label="Original Audio"), gr.Slider(1.0, 5.0, value=2.0, label="Volume Gain Factor")],
    outputs=gr.Audio(type="numpy", label="Amplified Audio"),
    title="Audio Volume Booster"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Audio Volume Booster

Original Audio Player
Volume Gain Factor: [---●-----] (2.0x)
Example 5: Noise Gate / Silence Truncation Filter
Filters out low-amplitude background noise samples from microphone recordings.
Python (audio_ex5.py)
import gradio as gr
import numpy as np

def noise_gate(audio, threshold):
    if audio is None:
        return None
    sr, y = audio
    # Zero out samples below threshold
    filtered = np.where(np.abs(y) < threshold, 0, y)
    return sr, filtered

demo = gr.Interface(
    fn=noise_gate,
    inputs=[gr.Audio(type="numpy", label="Speech Recording"), gr.Slider(100, 2000, value=500, label="Noise Threshold")],
    outputs=gr.Audio(type="numpy", label="Cleaned Audio"),
    title="Microphone Noise Gate Filter"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Microphone Noise Gate Filter

Speech Recording Player
Noise Threshold: [---●-----] (500)
Example 6: Dual Audio Track Merger (Voice & Background Music Mixer)
Mixes two uploaded audio tracks together into a single combined output stream.
Python (audio_ex6.py)
import gradio as gr
import numpy as np

def mix_audio(track1, track2):
    if track1 is None or track2 is None:
        return track1 or track2
    sr1, y1 = track1
    sr2, y2 = track2
    min_len = min(len(y1), len(y2))
    mixed = (y1[:min_len] * 0.6 + y2[:min_len] * 0.4).astype(np.int16)
    return sr1, mixed

demo = gr.Interface(
    fn=mix_audio,
    inputs=[gr.Audio(type="numpy", label="Voice Track"), gr.Audio(type="numpy", label="Music Track")],
    outputs=gr.Audio(type="numpy", label="Mixed Audio Output"),
    title="Multi-Track Audio Mixer"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Multi-Track Audio Mixer

Voice Track

Voice Player

Music Track

Music Player
Example 7: Audio Frequency Low-Pass Filter Simulation
Smooths out high-frequency audio noise using moving-average window filtering.
Python (audio_ex7.py)
import gradio as gr
import numpy as np

def low_pass_filter(audio, window_size=5):
    if audio is None:
        return None
    sr, y = audio
    # Simple moving average filter
    box = np.ones(int(window_size)) / window_size
    smoothed = np.convolve(y.astype(float), box, mode='same').astype(np.int16)
    return sr, smoothed

demo = gr.Interface(
    fn=low_pass_filter,
    inputs=[gr.Audio(type="numpy", label="Input Audio"), gr.Slider(1, 20, value=5, label="Smoothing Window")],
    outputs=gr.Audio(type="numpy", label="Filtered Audio"),
    title="Low-Pass Audio Filter Studio"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Low-Pass Audio Filter Studio

Input Audio Player
Smoothing Window: [---●-----] (5)
Example 8: Audio Waveform Plot Generator
Plots audio amplitude waveforms visually using Matplotlib and returns plot images.
Python (audio_ex8.py)
import gradio as gr
import matplotlib.pyplot as plt
import numpy as np

def plot_waveform(audio):
    if audio is None:
        return None
    sr, y = audio
    fig, ax = plt.subplots(figsize=(8, 3))
    ax.plot(y, color='#087f69', lw=0.5)
    ax.set_title("Audio Amplitude Waveform")
    ax.set_xlabel("Sample Index")
    ax.set_ylabel("Amplitude")
    ax.grid(True)
    return fig

demo = gr.Interface(
    fn=plot_waveform,
    inputs=gr.Audio(type="numpy", label="Upload Audio"),
    outputs=gr.Plot(label="Waveform Plot"),
    title="Audio Waveform Visualizer"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Audio Waveform Visualizer

Upload Audio Player
📈 Matplotlib Waveform Amplitude Chart Output
Example 9: Stereo to Mono Channel Converter
Downmixes dual-channel stereo audio recordings into single-channel mono audio streams.
Python (audio_ex9.py)
import gradio as gr
import numpy as np

def stereo_to_mono(audio):
    if audio is None:
        return None
    sr, y = audio
    if len(y.shape) > 1 and y.shape[1] == 2:
        # Average left and right channels
        mono = np.mean(y, axis=1).astype(np.int16)
        return sr, mono
    return sr, y

demo = gr.Interface(
    fn=stereo_to_mono,
    inputs=gr.Audio(type="numpy", label="Stereo Audio File"),
    outputs=gr.Audio(type="numpy", label="Converted Mono Audio"),
    title="Stereo to Mono Downmixer"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

### Stereo to Mono Downmixer

Stereo Audio File Player
Converted Mono Audio Player
Example 10: Multi-Format Voice Recorder & Transcription Hub (`gr.Blocks`)
Combines live voice recorders with transcript simulation blocks inside an enterprise layout.
Python (audio_ex10.py)
import gradio as gr

def transcribe_speech(audio):
    if audio is None:
        return "No audio recorded."
    return "Mock Speech-to-Text Transcription: Welcome to Nikita-Infotech Gradio Masterclass!"

with gr.Blocks() as demo:
    gr.Markdown("# 🎙️ Enterprise Voice Transcription Hub")
    with gr.Row():
        mic = gr.Audio(sources=["microphone"], label="Live Microphone")
        txt_out = gr.Textbox(label="Generated Transcript", lines=4)
    btn = gr.Button("Transcribe Audio", variant="primary")
    
    btn.click(transcribe_speech, inputs=mic, outputs=txt_out)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Web UI Visual Output Preview

# 🎙️ Enterprise Voice Transcription Hub

Live Microphone

🎙️ Record Audio

Generated Transcript

Mock Speech-to-Text Transcription...