Python基于Streamlit實現(xiàn)音頻處理示例詳解
基于Streamlit實現(xiàn)的音頻處理示例,包含錄音、語音轉(zhuǎn)文本、文件下載和進度顯示功能,整合了多個技術(shù)方案:
一、環(huán)境準備
# 安裝依賴庫 pip install streamlit streamlit-webrtc audio-recorder-streamlit openai-whisper python-dotx
二、完整示例代碼
import streamlit as st
from audio_recorder_streamlit import audio_recorder
import whisper
import os
from datetime import datetime
# 初始化模型
@st.cache_resource
def load_whisper_model():
return whisper.load_model("base") # 使用基礎版模型
model = load_whisper_model()
# 界面布局
st.title("?? 音頻處理工作流")
col1, col2 = st.columns(2)
with col1:
# 音頻錄制組件
audio_bytes = audio_recorder(
text="點擊錄音",
recording_color="#e87070",
neutral_color="#6aa36f",
icon_name="microphone",
sample_rate=16000
)
# 保存錄音文件
if audio_bytes:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
audio_path = f"audio_{timestamp}.wav"
with open(audio_path, "wb") as f:
f.write(audio_bytes)
st.session_state.audio_path = audio_path
st.audio(audio_bytes, format="audio/wav")
with col2:
# 語音轉(zhuǎn)文本功能
if 'audio_path' in st.session_state and st.button("開始轉(zhuǎn)換"):
progress_bar = st.progress(0)
status_text = st.empty()
try:
status_text.text("加載音頻文件...")
progress_bar.progress(20)
# 使用Whisper進行轉(zhuǎn)換
status_text.text("語音識別中...")
result = model.transcribe(st.session_state.audio_path)
progress_bar.progress(80)
# 顯示結(jié)果
st.subheader("轉(zhuǎn)換結(jié)果")
st.code(result["text"], language="text")
st.session_state.text_result = result["text"]
# 生成下載按鈕
with st.expander("下載選項"):
st.download_button(
label="下載文本",
data=st.session_state.text_result,
file_name=f"transcript_{timestamp}.txt",
mime="text/plain"
)
with open(st.session_state.audio_path, "rb") as f:
st.download_button(
label="下載音頻",
data=f,
file_name=audio_path,
mime="audio/wav"
)
progress_bar.progress(100)
status_text.text("處理完成!")
except Exception as e:
st.error(f"處理失敗: {str(e)}")
progress_bar.progress(0)
三、核心功能解析
1.音頻錄制
- 使用audio-recorder-streamlit庫實現(xiàn)瀏覽器原生錄音
- 支持設置采樣率(16kHz)和錄音按鈕樣式
- 自動保存為WAV格式文件
2.語音識別
- 采用OpenAI Whisper本地模型進行轉(zhuǎn)換
- 支持多語言識別,基礎模型大小約150MB
- 通過@st.cache_resource緩存模型提升性能
3.進度管理
- 分階段更新進度條(加載→識別→完成)
- 使用st.spinner實現(xiàn)加載動畫
- 異常處理機制保障流程穩(wěn)定性
4.文件下載
- 生成帶時間戳的唯一文件名
- 同時提供文本和音頻下載
- 支持MIME類型自動識別
四、高級優(yōu)化方案
1.云端部署
# 在HuggingFace Spaces部署時添加配置 STREAMLIT_SERVER_PORT = 8501
2.性能提升
使用量化版Whisper模型(tiny.en/small.en)
啟用GPU加速(需配置CUDA環(huán)境)
model = whisper.load_model("base", device="cuda")
3.擴展功能
添加音頻可視化
import matplotlib.pyplot as plt from scipy.io import wavfile rate, data = wavfile.read(audio_path) plt.specgram(data, Fs=rate) st.pyplot(plt)
五、部署注意事項
依賴管理
# requirements.txt streamlit>=1.28 openai-whisper==20231106 audio-recorder-streamlit==0.1.7
瀏覽器兼容性
需啟用HTTPS協(xié)議訪問錄音功能
推薦使用Chrome/Firefox最新版
資源監(jiān)控
# 監(jiān)控內(nèi)存使用 ps -o pid,user,%mem,command ax | grep streamlit
該方案整合了本地模型推理與Streamlit的交互優(yōu)勢,相比純API方案可節(jié)省90%的云端調(diào)用成本。通過進度分段顯示和異常捕獲機制,使長時間任務具備更好的用戶體驗。
到此這篇關(guān)于Python基于Streamlit實現(xiàn)音頻處理示例詳解的文章就介紹到這了,更多相關(guān)Python Streamlit音頻處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
TensorFlow 實戰(zhàn)之實現(xiàn)卷積神經(jīng)網(wǎng)絡的實例講解
下面小編就為大家分享一篇TensorFlow 實戰(zhàn)之實現(xiàn)卷積神經(jīng)網(wǎng)絡的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02
Pandas Dataframe數(shù)據(jù)幀的迭代之iterrows(),itertuples(),items()詳
這篇文章主要介紹了Pandas Dataframe數(shù)據(jù)幀的迭代之iterrows(),itertuples(),items()使用,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04

