import gradio as gr import numpy as np import wave import os from pydub import AudioSegment # Function to create audio with customizable fade-out def create_audio_with_fade_out(half_life): sample_rate = 44100 frequency = 440 # A4 note (440 Hz) duration = 2 # seconds t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False) # Exponential decay based on user-selected half-life fade_out_factor = np.exp(-np.log(2) * t / half_life) audio_data = 0.5 * np.sin(2 * np.pi * frequency * t) * fade_out_factor # File naming based on half-life half_life_str = f"{half_life:.3f}".replace(".", "_") # Format filename wav_path = f"generated_{half_life_str}s.wav" # Save as WAV with wave.open(wav_path, 'wb') as wf: wf.setnchannels(1) # Mono wf.setsampwidth(2) # 16-bit PCM wf.setframerate(sample_rate) wf.writeframes((audio_data * 32767).astype(np.int16)) return wav_path # Convert WAV to MP3 def convert_to_mp3(half_life): wav_path = create_audio_with_fade_out(half_life) mp3_path = wav_path.replace(".wav", ".mp3") audio = AudioSegment.from_wav(wav_path) audio.export(mp3_path, format="mp3") return mp3_path # Play last generated MP3 def play_last_audio(half_life): half_life_str = f"{half_life:.3f}".replace(".", "_") mp3_path = f"generated_{half_life_str}s.mp3" if os.path.exists(mp3_path): return mp3_path else: return None # No file found # Gradio UI with gr.Blocks() as app: gr.Markdown(""" # 🎵 Sound Generator with Custom Fade-out **Created on:** February 14, 2025 **Made by:** ESP **Description:** This app generates a **sine wave sound** that fades out based on a user-defined **half-life**. - Adjust the **half-life** with the slider (1s to 0.001s). - Click **"Generate MP3"** to create a new sound. - Click **"Play Last MP3"** to listen to the last generated sound. - The file name includes the **half-life value** (e.g., `generated_0_5s.mp3`). """) # Slider for Half-Life Selection half_life_slider = gr.Slider(minimum=0.001, maximum=1, value=0.5, label="Half-Life (seconds)", step=0.001) generate_button = gr.Button("Generate MP3") play_button = gr.Button("Play Last MP3") audio_output = gr.File() audio_player = gr.Audio() generate_button.click(convert_to_mp3, inputs=[half_life_slider], outputs=audio_output) play_button.click(play_last_audio, inputs=[half_life_slider], outputs=audio_player) app.launch()