优化语音发送逻辑

This commit is contained in:
liuwei
2025-05-29 17:42:47 +08:00
parent 3659eb7d99
commit df3ee777b2
2 changed files with 14 additions and 4 deletions

View File

@@ -266,8 +266,18 @@ def api_send_message():
if 'file' not in request.files:
return jsonify({'success': False, 'message': '未上传文件'})
file = request.files['file']
if file.name.endswith('.mp3'):
format_str = "mp3"
elif file.name.endswith('.wav'):
format_str = "wav"
else:
return jsonify({
'success': False,
'data': {
}
})
client_msg_id, create_time, new_msg_id = loop.run_until_complete(
server.client.send_voice_message(wxid, file.read(), format="mp3")
server.client.send_voice_message(wxid, file.read(), format=format_str)
)
return jsonify({
'success': True,

View File

@@ -319,7 +319,7 @@ class MessageMixin(WechatAPIClientBase):
if not self.wxid:
raise UserLoggedOut("请先登录")
elif format not in ["amr", "wave", "mp3", "silk", "speex"]:
elif format not in ["amr", "wav", "mp3", "silk", "speex"]:
raise ValueError("format must be one of amr, wav, mp3")
# read voice to byte
@@ -337,7 +337,7 @@ class MessageMixin(WechatAPIClientBase):
if format.lower() == "amr":
audio = AudioSegment.from_file(BytesIO(voice_byte), format="amr")
voice_base64 = base64.b64encode(voice_byte).decode()
elif format.lower() == "wave":
elif format.lower() == "wav":
audio = AudioSegment.from_file(BytesIO(voice_byte), format="wav").set_channels(1)
audio = audio.set_frame_rate(self._get_closest_frame_rate(audio.frame_rate))
voice_base64 = base64.b64encode(
@@ -354,7 +354,7 @@ class MessageMixin(WechatAPIClientBase):
duration = len(audio)
# Type AMR = 0, MP3 = 2, SILK = 4, SPEEX = 1, WAVE = 3 VoiceTime :音频长度 1000为一秒
format_dict = {"amr": 0, "wave": 3, "mp3": 2, "silk": 4, "speex": 1}
format_dict = {"amr": 0, "wav": 3, "mp3": 2, "silk": 4, "speex": 1}
# {
# "Base64": "string",
# "ToWxid": "string",