执行在网页中使用PyAudio的python脚本

时间:2018-05-30 08:42:23

标签: javascript php python-3.x audio-recording pyaudio

我有一个python脚本,它使用pyaudio使用麦克风录制音频,代码将语音转换为文本。它在终端上工作得非常好。这是python代码的一部分:

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                output=True,
                frames_per_buffer=CHUNK)


async def send_audio(ws):
    # Starts recording of microphone
    print("* READY *")
    start = time.time()
    while True:
        try:
            #print(".")
            data = stream.read(CHUNK)
            await ws.send(data)
            ##if time.time() - start > 30:    # Records for n seconds
                ##await ws.send(json.dumps({'action': 'stop'}))
                ##return False
        except Exception as e:
            print(e)
            return False
        except KeyboardInterrupt:  # allow Ctrl + C to shut down the program
            await ws.send(json.dumps({'action': 'stop'}))
            return False

    # Stop the stream and terminate the recording
    stream.stop_stream()
    stream.close()
    p.terminate()


async def speech_to_text():
    async with websockets.connect(url, extra_headers=token_header) as conn:
        # Send request to watson and waits for the listening response
        send = await conn.send(json.dumps(params))
        rec = await conn.recv()
        print(rec)
        asyncio.ensure_future(send_audio(conn))
        w=0
        global lst
        # Keeps receiving transcript until we have the final transcript
        while True:
            try:
                rec = await conn.recv()
                parsed = json.loads(rec)
                transcript = parsed["results"][0]["alternatives"][0]["transcript"]

                #print(parsed)
                if "results" in parsed:
                    if len(parsed["results"]) > 0:
                        if "final" in parsed["results"][0]:
                            if parsed["results"][0]["final"]:
                                #conn.close()
                                #return False
                                print(transcript)
                                lst.append(transcript)
                                lst.append("\n")
                                pass
            except KeyError:
                conn.close()
                return False

# Starts the application loop
loop = asyncio.get_event_loop()
loop.run_until_complete(speech_to_text())
loop.close()

现在,我想通过单击按钮在网页中调用此脚本。我尝试在php中使用exec()和shell_exec():

<div>
<?php
echo "<h3>POST:</h3>";
print_r($_POST);
if(isset($_POST["submit"])){
 print_r (shell_exec("cd / && python C:/xampp/htdocs/heyy/postibm.py"));

}
?>

<form method="post"
action="try.php ">
<input type="submit" name="submit"
value="Submit">
</form>
</div>

但点击按钮后,页面卡在加载屏幕上并且没有响应。如果我更换了&#34; postibm.py&#34;用简单的&#34; helloworld.py&#34;打印你好世界,它的工作原理。任何想法问题在哪里?或者更好的方法来解决这个问题?

0 个答案:

没有答案