import gradio as gr
def predict_audio():
return "Welcome to my website!"
audio_recorder = gr.inputs.Audio(recording=True)
start_button = gr.outputs.Button(type="button", label="开始录音")
stop_button = gr.outputs.Button(type="button", label="停止录音")
text_box = gr.outputs.Text()
interface = gr.Interface(fn=predict_audio, inputs=audio_recorder,
outputs=[start_button, stop_button, text_box])
interface.launch()
后端代码:
python
import os
import time
from flask import Flask, request, jsonify
app = Flask(__name__)
TMP_AUDIO_FILE = "temp.wav"
RECORD_TIME_LIMIT = 5 # in seconds
@app.route('/start_recording', methods=['POST'])
def start_recording():
# Start recording audio
audio = request.files['audio_data']
audio.save(TMP_AUDIO_FILE)
return jsonify(status="STARTED")
@app.route('/stop_recording', methods=['POST'])
def stop_recording():
# Save recorded audio to temporary file
audio = request.files['audio_data']
audio.save(TMP_AUDIO_FILE)
# Get the recorded audio file size and duration
audio_size = os.path.getsize(TMP_AUDIO_FILE)
audio_duration = int(audio_size / 32000) # Assuming 16-bit, 16K sample rate
# Check if audio has voice
voice_detected = check_voice(TMP_AUDIO_FILE)
if voice_detected:
# Trim audio to keep only the voice part
trim_audio(TMP_AUDIO_FILE, audio_duration)
# Process audio and get the transcription
transcription = process_audio(TMP_AUDIO_FILE)
# Return the transcription to the client
return jsonify(status="SUCCESS", transcription=transcription)
else:
# Delete the recorded audio
os.remove(TMP_AUDIO_FILE)
return jsonify(status="NO_VOICE_DETECTED")
def check_voice(file_path):
# Check if there is voice in the audio file
# using some voice detection library
return True
def trim_audio(file_path, duration):
# Trim the audio file to keep only the voice part
# using some audio editing library
return
def process_audio(file_path):
# Process the audio file to get the transcription
# using some speech recognition library
return "Hello world!"
if __name__ == '__main__':
app.run(debug=True)