简介:本文详解如何通过Python快速接入免费语音识别API,覆盖环境配置、API选择、代码实现及优化技巧,帮助开发者低成本构建语音转文本功能,适合个人项目及轻量级企业应用。
当前主流的免费语音识别API包括Google Speech-to-Text(免费层)、AssemblyAI免费计划、Vosk离线模型及微软Azure Cognitive Services免费额度。其中,Google Speech-to-Text免费层每月提供60分钟音频处理,适合轻量级需求;AssemblyAI提供500分钟/月的免费转录,支持实时流式处理;Vosk作为离线方案,无需网络依赖,但需下载语言模型(约2GB)。微软Azure的免费额度为500万字符/月,但需绑定信用卡,可能限制部分用户。
使用Python 3.8+版本,推荐通过虚拟环境管理依赖:
python -m venv asr_envsource asr_env/bin/activate # Linux/macOSasr_env\Scripts\activate # Windows
pip install requests
pip install webrtcvad
需额外安装ffmpeg(通过系统包管理器或下载静态文件)。
pip install pydub
import requestsimport jsondef google_asr(audio_path, api_key):url = "https://speech.googleapis.com/v1/speech:recognize?key=" + api_keyheaders = {"Content-Type": "application/json"}# 读取音频文件(需为FLAC格式,16000Hz采样率)with open(audio_path, "rb") as f:audio_data = f.read()# 构造请求体payload = {"config": {"encoding": "FLAC","sampleRateHertz": 16000,"languageCode": "zh-CN" # 中文普通话},"audio": {"content": base64.b64encode(audio_data).decode("utf-8")}}response = requests.post(url, headers=headers, data=json.dumps(payload))return response.json()# 示例调用result = google_asr("test.flac", "YOUR_API_KEY")print(result["results"][0]["alternatives"][0]["transcript"])
def convert_to_flac(input_path, output_path):
audio = AudioSegment.from_file(input_path)
audio = audio.set_frame_rate(16000).set_channels(1)
audio.export(output_path, format=”flac”)
- **错误处理**:捕获API限额错误(HTTP 429)并实现重试机制。### 四、AssemblyAI免费计划接入#### 4.1 注册与API令牌获取1. 访问AssemblyAI官网,注册免费账户。2. 在控制台生成API令牌(Token)。#### 4.2 实时流式处理示例```pythonimport requestsimport jsondef assemblyai_stream(audio_stream, token):url = "https://api.assemblyai.com/v2/stream"headers = {"authorization": token,"content-type": "audio/x-raw","transfer-encoding": "chunked"}# 分块发送音频数据(示例为伪代码)for chunk in audio_stream:requests.post(url, headers=headers, data=chunk)# 获取最终转录结果(需记录转录ID)transcription_url = f"https://api.assemblyai.com/v2/transcript/{transcript_id}"response = requests.get(transcription_url, headers={"authorization": token})return response.json()["text"]
vosk-model-small-cn-0.3)。model = Model(“path/to/vosk-model-small-cn-0.3”)
recognizer = KaldiRecognizer(model, 16000)
#### 5.2 实时识别实现```pythonimport pyaudiodef vosk_realtime():p = pyaudio.PyAudio()stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)while True:data = stream.read(4000) # 每次读取4000字节(约0.25秒)if recognizer.AcceptWaveForm(data):result = json.loads(recognizer.Result())print(result["text"])# 示例调用vosk_realtime()
INVALID_AUDIO错误。languageCode="zh-CN"。通过以上方案,开发者可在零成本前提下,快速构建高可用的语音识别功能,覆盖从个人项目到企业级应用的多种场景。