实现单例任务,可推送新任务功能,垃圾回收功能。

This commit is contained in:
2025-04-27 00:46:21 +08:00
parent 8aa87900bf
commit 484c20a5ef
4 changed files with 92 additions and 46 deletions

View File

@@ -8,6 +8,8 @@ from machine import Pin, I2S
import ubinascii
import urandom
import shared_vars
# I2S 引脚配置
BCLK_PIN = 13
WS_PIN = 12
@@ -38,7 +40,6 @@ def init_i2s():
ibuf=BUFFER_SIZE) # 输入缓冲区大小
return i2s
class InterphoneHandler:
def play_wav_file(self, data):
@@ -67,46 +68,46 @@ class InterphoneHandler:
if 'audio_out' in locals():
audio_out.deinit()
def play_audio_stream(self, i2s, url):
def stream_and_play(self, data):
current_task_id = shared_vars.handle_task_id
url = "https://iot.julecn.com/interphone/get_voice?name=" + data['name'] # 替换为音频文件的URL
print(url)
try:
# 添加请求头信息
print("添加请求头信息")
headers = {
'User-Agent': 'MicroPython v1.0.0'
}
# 发送 HTTP 请求,获取流式响应
print("发送 HTTP 请求,获取流式响应")
response = urequests.get(url, headers=headers, stream=True)
# 检查响应状态码
print("检查响应状态码")
if response.status_code != 200:
print(f"请求失败,状态码: {response.status_code}")
response.close()
return
# 解析 WAV 头部
print("解析 WAV 头部")
header = response.raw.read(44)
if len(header) != 44 or header[0:4] != b'RIFF' or header[8:12] != b'WAVE' or header[12:16] != b'fmt ':
print(header)
raise ValueError("Not a valid WAV file")
# 提取采样率、位深、声道数
print("提取采样率、位深、声道数")
global SAMPLE_RATE, BITS_PER_SAMPLE, CHANNELS
SAMPLE_RATE = int.from_bytes(header[24:28], 'little')
BITS_PER_SAMPLE = int.from_bytes(header[34:36], 'little')
CHANNELS = int.from_bytes(header[22:24], 'little')
# 重新初始化 I2S 输出
print("初始化 I2S 输出")
audio_out = init_i2s()
# 开始流式播放
chunk_size = 1024
while True:
print("开始流式播放")
chunk_size = 512
while shared_vars.handle_task_id == current_task_id:
chunk = response.raw.read(chunk_size)
if not chunk:
break
audio_out.write(chunk)
except Exception as e:
print("Playback error:", e)
finally:
@@ -114,26 +115,8 @@ class InterphoneHandler:
audio_out.deinit()
if 'response' in locals():
response.close()
def stream_and_play(self, data):
i2s = init_i2s()
url = "http://iot.julecn.com/interphone/get_voice?name=" + data['name'] # 替换为音频文件的URL
print(url)
self.play_audio_stream(i2s, url)
def generate_random_hex():
# 初始化一个空的字节数组,用于存储随机字节
random_bytes = bytearray()
# 循环 4 次,每次生成 32 位4 字节)的随机数
for _ in range(4):
# 生成 32 位随机数
rand_32_bits = urandom.getrandbits(32)
# 将 32 位随机数转换为 4 字节,并添加到字节数组中
random_bytes.extend(rand_32_bits.to_bytes(4, 'big'))
# 将随机字节转换为十六进制字符串
hex_string = ubinascii.hexlify(random_bytes).decode()
return hex_string
print('音频播放完成')
def stop_playing(self, data):
print("停止播放音频")
pass