Skip to main content
 首页 » 编程设计

python之是否可以在 Django 上使用 Python SpeechRecognition

2024年10月01日43开发

我有以下脚本可以在终端中运行:

所做的只是将麦克风语音转换为文本。

import speech_recognition as sr 
 
# obtain audio from microphone 
r = sr.Recognizer() 
with sr.Microphone() as source: 
    print("Say something!") 
    audio = r.listen(source) 
 
try: 
    # for testing purposes, we're just using the default API key 
    # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")` 
    # instead of `r.recognize_google(audio)` 
    print("Google Speech Recognition thinks you said " + r.recognize_google(audio)) 
except sr.UnknownValueError: 
    print("Google Speech Recognition could not understand audio") 
except sr.RequestError as e: 
    print("Could not request results from Google Speech Recognition service; {0}".format(e)) 

是否有可能在按下按钮后在 Django 上进行这项工作? 像这样的东西:

查看:

import speech_recognition as sr 
 
# Create your views here. 
def index(request): 
    return render(request, 'app/index.html') 
 
def text(request): 
    r = sr.Recognizer() 
    with sr.Microphone() as source: 
        #print("Say something!") 
        audio = r.listen(source) 
 
    try: 
        # for testing purposes, we're just using the default API key 
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")` 
        # instead of `r.recognize_google(audio)` 
        speech = r.recognize_google(audio) 
    except sr.UnknownValueError: 
        speech = "Google Speech Recognition could not understand audio" 
    except sr.RequestError as e: 
        speech = "Could not request results from Google Speech Recognition service; {0}".format(e) 
    return render(request, 'app/text', {'speech': speech}) 

模板:

<form action="/text/" method="post"> 
    <input type="button" value="Start listening" /> 
</form> 

这可能吗?我是接近还是根本不接近?

请您参考如下方法:

Django 无法访问用户的计算机,因此如果您尝试从麦克风录音,您将使用服务器的麦克风(如果有的话)。

您需要record using JS/HTML5然后将数据发送到 django 以使用 AJAX 进行处理。您甚至可以流式传输它,但这可能不值得付出努力。