这一遍,写网页端传声音到python端走websocket。
不二话,上代码打样。 python音频服务端
import base64
import asyncio
import websockets
import cv2
import math
import np
import pyaudio
import wave
import time
import threading
import matplotlib.pyplot as plt
chunk = 4096
sample_format = pyaudio.paInt16
channels = 2
fs = 44100
p = pyaudio.PyAudio()
micstream = p.open(format=sample_format,
channels=channels,
rate=fs,
frames_per_buffer=chunk,
input=True)
stream2 = p.open(format=sample_format,
channels=channels,
rate=fs,
frames_per_buffer=chunk,
output=True)
async def echo(websocket, path):
print(websockets.serve)
async for message in websocket:
stream2.write(message)
y=[]
for i in range(1):
m=micstream.read(chunk)
y.append(m)
if len(message )>1:await websocket.send(y)
async def main():
async with websockets.serve(echo, "192.168.1.102", 8765):
await asyncio.Future()
asyncio.run(main())
html网页端,上代码 点击设备授权就开始跑代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no">
<meta name="format-detection" content="telephone=no">
<title>音量</title>
<style>
</style>
</head>
<body>
<div id="status">预备开始</div>
<audio id="video" src=""></audio>
<a onclick='aa()'>开始</a> <a onclick='bb()'>结束</a>
<script type="text/javascript">
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({
video: false,
audio: {
sampleRate: 44100,
channelCount: 2,
volume: 1.0,
sampleBits:16
}
}).then((stream) => {
var audioContext= new AudioContext();
const socket = new WebSocket('ws://192.168.1.102:8765');
mediaStreamSource = audioContext.createMediaStreamSource(stream);
scriptProcessor = audioContext.createScriptProcessor(4096,2,2);
mediaStreamSource.connect(scriptProcessor);
scriptProcessor.connect(audioContext.destination);
var c=[]
var i2=0;
scriptProcessor.onaudioprocess = function(e) {
let buffer = e.inputBuffer.getChannelData(0);
let buffer1 = e.inputBuffer.getChannelData(1);
var v = new Int16Array(buffer.length*2)
for (var i=0;i<buffer.length;i++){
v[i2]=Math.trunc(buffer[i]*30000);
i2++;
v[i2]=Math.trunc(buffer1[i]*30000);
i2++;
}
i2=0
console.log(c.length,v)
socket.send(v)
};
}).catch((error) => {
});
} else {
}
</script>
</body>
</html>
本例完。 再说说遥控机器人的思路吧,思想的巨人行动的矮子。对不起我是废物没有精力完成,虽然真的对于我来说很简单。 首先遥控和机器人的动作,可以拿来训练神经网络堆数据集。 慢慢可以实现AI化,让它成为我们的狗腿子那不是so easy。
网页端当机器人也还行把,网页通串口可以控制舵机,读取陀螺仪算姿态会发现很多功能是现成的。^ ^
|