Last active
August 27, 2024 07:05
-
-
Save Helw150/4baeb6e51bda106903b8cbc79720ea14 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import gradio as gr | |
import math | |
import numpy as np | |
import time | |
import io | |
import wave | |
def wave_header_chunk(frame_input=b"", channels=1, sample_width=2, sample_rate=24000): | |
# This will create a wave header then append the frame input | |
# It should be first on a streaming wav file | |
# Other frames better should not have it (else you will hear some artifacts each chunk start) | |
wav_buf = io.BytesIO() | |
with wave.open(wav_buf, "wb") as vfout: | |
vfout.setnchannels(channels) | |
vfout.setsampwidth(sample_width) | |
vfout.setframerate(sample_rate) | |
vfout.writeframes(frame_input) | |
wav_buf.seek(0) | |
return wav_buf.read() | |
def yield_from_stream(): | |
# Necessary Start of Audio Stream | |
yield wave_header_chunk() | |
# Dummy Audio Generation with Sin Waves | |
volume = 10000 # range [0.0, 1.0] | |
fs = 48000 # sampling rate, Hz, must be integer | |
duration = 0.25 # in seconds, may be float | |
f = 440.0 # sine frequency, Hz, may be float | |
# generate samples, note conversion to float32 array | |
num_samples = int(fs * duration) | |
while True: | |
if f == 440.0: | |
f = 880.0 | |
else: | |
f = 440.0 | |
# Generated Audio To Add to Stream | |
samples = np.array( | |
[ | |
int(volume * math.sin(2 * math.pi * k * f / fs)) | |
for k in range(0, num_samples) | |
], | |
dtype=np.int16, | |
) | |
# Yield to Stream | |
yield samples.tobytes() | |
# Dummy Delay To Simulate Generation Time | |
time.sleep(0.5) | |
with gr.Blocks() as demo: | |
out = gr.Audio( | |
streaming=True, | |
autoplay=True, | |
interactive=False, | |
) | |
start = gr.Button("Start Stream") | |
start.click(yield_from_stream, [], [out]) | |
demo.launch(share=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment