踩大坑:json格式存储wav二进制内容

需求描述:

需要将wav音频文件以二进制的形式读出,存放到 json 中,发送post请求到服务,服务解析json,得到二进制内容后放进ASR模型得出转录结果。

记一次坑:

# 将wav以二进制形式读出存放到json中
f = open("zh_test_16k.wav","rb+")
content = f.read()
request_dict['audio'] = str(content)
with open('request.json', 'w') as file:
     	file.write(json.dumps(request_dict)) 
f.close()

通过 curl管道传输request.json中的内容
(网上的命令杂七杂八,记录正确命令为 -X
-d参数房放前面,url放后面,且url用引号)

curl -X POST -d @request64.json --header “Content-Type:application/json” ‘localhost:7000/foundry_module/executor?executor=api_executor&module=asr_uni’

# 从服务端得到数据
datas = self.rfile.read(int(self.headers['content-length'])) 
datas = json.loads(datas)
wav_content = datas["audio"].encode()

encode():str转为bytes
decode():bytes转为str

wav_content # type(wav_content)= bytes 
f = open("zh_test_16k.wav","rb+")
content = f.read()
# type(content)= bytes
if(wav_content==content):
	print("相等")

始终不能输出"相等",此时已经快调疯了

解决办法

先将二进制内容通过base64编码

# import foundry;
import base64;
import hashlib;
import json

encoded = base64.b64encode(open('zh_test_16k.wav', 'rb').read());                     
#decoded = base64.b64decode(encoded)
request_dict = {}
f = open('zh_test_16k.wav','rb+')
sound_wav_rb = f.read()
request_dict['audio'] = str(encoded)
request_dict['audio_format'] = 0
request_dict['sample_rate'] = 0
request_dict['lang'] = 0
with open('request64.json', 'w') as file:
     file.write(json.dumps(request_dict)) 
f.close()

传输request64.json文件内容

curl -X POST -d @request64.json --header “Content-Type:application/json” ‘localhost:7000/foundry_module/executor?executor=api_executor&module=asr_uni’

字符串截取base64编码不包含’b’ 和引号的内容,再解码,最后放入模型

datas = self.rfile.read(int(self.headers['content-length']))
datas = json.loads(datas)
wav_content = datas["audio"][2:-1]
wav_content = base64.b64decode(wav_content)

踩坑原因

json存在编译格式的问题,会导致原二进制文件内容多加 ”/“,因此不与原wav文件的二进制内容一致

下次不要直接以二进制读的方式,将内容存到json中了!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值