用于谷歌语音API的MP3到FLAC

2024-06-02 07:50:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找到一个简单的方法,把MP3发送到Google进行语音识别。目前,我正在使用一个子进程来调用SoX,它将其转换为WAV。然后,使用SpeechRecognition,它再次将其转换为FLAC。理想情况下,我想要一个更便携(不是操作系统特定)的方式解码MP3,并发送它没有中间文件保存等。在

以下是我目前的情况:

import speech_recognition as sr
import subprocess
import requests

audio = requests.get('http://somesite.com/some.mp3')

with open('/tmp/audio.mp3', 'wb') as file:
    file.write(audio.content)

subprocess.run(['sox', '/tmp/audio.mp3', '/tmp/audio.wav'])

r = sr.Recognizer()
with sr.WavFile('/tmp/audio.wav') as source:
    audio = r.record(source)

result = r.recognize_google(audio)
del r

我尝试过直接使用SpeechRecognition中包含的FLAC二进制文件,但是输出只是静态的。我不太喜欢在Git上发布二进制文件,但如果这是唯一的方法,我会的。在

一些重要环节:

SR's code for speech recognition

SR's code for WAV to FLAC

编辑

我正在考虑以FLAC二进制文件的方式分发SoX,如果SoX的许可证允许的话,每个操作系统一个。。。在

再想一想,软件许可证是令人困惑的,我不想搞得一团糟。在


Tags: 文件方法importas二进制情况mp3audio
1条回答
网友
1楼 · 发布于 2024-06-02 07:50:31

我决定这么做:

import subprocess
import requests
import shutil
import glob
import json

audio = requests.get('http://somesite.com/some.mp3')
sox = shutil.which('sox') or glob.glob('C:\Program Files*\sox*\sox.exe')[0]
p = subprocess.Popen(sox + ' -t mp3 - -t flac - rate 16k', stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell = True)
stdout, stderr = p.communicate(audio.content)
url = 'http://www.google.com/speech-api/v2/recognize?client=chromium&lang=en-US&key=AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw'
headers = {'Content-Type': 'audio/x-flac; rate=16000'}
response = requests.post(url, data = stdout, headers = headers).text

result = None
for line in response.split('\n'):
    try:
        result = json.loads(line)['result'][0]['alternative'][0]['transcript']
        break
    except:
        pass

这更像是一个中间地带,我想从SR模块中借用一些东西。它需要用户安装SoX,但是应该在所有操作系统上工作,并且没有任何中间文件。不过,我只在Linux上测试过它。在

相关问题 更多 >