关于实现base64文件解码转mp3实现播放功能
1.简介
需求:大致接收一个python后端传输的一段实时录音文件,以base64编码格式为主的,java进行处理,转MP3文件,实现播放小功能。
**一、java对接python后端controller层代码**:
核心:对接收的base64编码文件进行解码处理
方法: 采用Base64.Decoder decoder = Base64.getDecoder();进行解码,采用IO流将文件写入,实现mp3功能播放
@PostMapping("/speech")
public Result speech(@RequestBody SyncListPojo<Speech> syncListPojo, HttpServletRequest request) {
List<Speech> speeches = syncListPojo.getData();
if (null == speeches || speeches.isEmpty()) {
return Result.fail("同步数据为空!");
}
UserDevices current = (UserDevices) request.getAttribute(UserDeviceService.CurrentDevice);
System.out.println("current = " + current);
if (null == current) {
return Result.fail("设备不可用!");
}
for (Speech speech : speeches) {
//base64 转音频 2021-7-19 start
//解码
Base64.Decoder decoder = Base64.getDecoder();
String fileDir = upload + “speech” + File.separator + DateUtil.getDateString(new Date(), “yyyy-MM-dd”);
String fileDir1 =“speech” + File.separator + DateUtil.getDateString(new Date(), “yyyy-MM-dd”);
File file = new File(fileDir);
if(!file.exists()){
file.mkdirs();
}
String fileName = UUID.randomUUID()+".wav";
String filePath = fileDir + File.separator + fileName;
String filePath1 = fileDir1 + File.separator + fileName;
byte[] decode = decoder.decode(speech.getBasePath());
try {
for (int i = 0; i <decode.length ; i++) {
if (decode[i] < 0) {
decode[i] += 256;
}
}
FileOutputStream out = new FileOutputStream(filePath);
out.write(decode);
out.flush();
out.close();
if(null != filePath){
speech.setBasePath(filePath1);
speech.setSpeechType(1);
}
} catch (IOException e) {
e.printStackTrace();
log.error(“base64字符串转化成mp3异常,{}”,e);
}
//base64 转音频 2021-7-19 end
if (StringUtil.isEmpty(speech.getNumbers())) {
return Result.fail(JSON.toJSONString(speech) + “numbers不能为空”);
} else if (StringUtil.isEmpty(speech.getCreateDate())) {
return Result.fail(JSON.toJSONString(speech) + “createDate不能为空”);
} else if (StringUtil.isEmpty(speech.getSpeechType())) {
return Result.fail(JSON.toJSONString(speech) + “speechType不能为空”);
} else if (StringUtil.isEmpty(speech.getSpeechContent())) {
return Result.fail(JSON.toJSONString(speech) + “speechContent不能为空”);
}
speech.setId(StringUtil.getUUID());
speech.setUserId(current.getUserId());
speech.setUserName(current.getUserName());
speech.setLocationId(current.getLocationId());
speech.setLocationName(current.getLocationName());
speech.setDeviceId(current.getId());
speech.setDeviceName(current.getName());
}
return Result.success(speechClient.inserts(speeches), "同步成功!");
}