@Api(tags = {"APP音频合成"})
@RestController
@RequestMapping("/app")
public class AudioFileController {@Autowiredprivate IAudioFileService audioFileService;/*** 合成音频** @param audioFile 录音文件* @param audioUrl 背景音乐url链接* @return*/@ApiOperation(value = "合成音频", notes = "【请求参数】<br> MultipartFile audioFile 录音文件" +" <br> String audioUrl 背景音乐url链接")@PostMapping("/mergeAudioFile")public AjaxResult mergeAudioFile(@RequestPart("audioFile") MultipartFile audioFile,@RequestParam String audioUrl) {return audioFileService.mergeAudioFile(audioFile, audioUrl);}
}
/*** 合成音频文件* 该方法将合并上传的音频文件和URL指定的音频文件,并上传到阿里云OSS** @param audioFile 录音文件* @param audioUrl 背景音乐url链接* @return 合成后音频文件的下载链接*/public AjaxResult mergeAudioFile(MultipartFile audioFile, String audioUrl) {// 记录方法开始时间Instant start = Instant.now();File mergedAudioFile = null;String fileUrl = "";try {// 1. 下载通过URL提供的音频文件byte[] audioFileFromUrl = downloadAudioFromUrl(audioUrl);// 2. 获取上传的音频文件byte[] uploadedAudioFile = audioFile.getBytes();// 3. 合并音频文件mergedAudioFile = mergeAudioFiles(uploadedAudioFile, audioFileFromUrl);// 4. 上传合成后的音频文件到阿里云OSS
// fileUrl = ossUtils.uploadFileToOSS(mergedAudioFile, null, true);fileUrl = ossUtils.uploadFile(mergedAudioFile, null, true, null); //分片上传AjaxResult ajaxResult = new AjaxResult();Map<String, String> map = Maps.newHashMap();map.put("mergeAudioUrl",fileUrl);ajaxResult.put("code", 200);ajaxResult.put("msg", "合成音频成功");ajaxResult.put("data", map);// 5. 返回OSS文件的下载链接return ajaxResult;} catch (Exception e) {return AjaxResult.error("合成音频失败:" + e.getMessage());}finally {// 删除临时音频文件if (mergedAudioFile != null && mergedAudioFile.exists()) {mergedAudioFile.delete();}// 记录方法结束时间Instant end = Instant.now();// 打印耗时long duration = java.time.Duration.between(start, end).toMillis();log.info("合成音频文件的耗时: {} 毫秒, mergeAudioUrl: {}", duration, fileUrl);}}/*** 从URL下载音频文件** @param audioUrl 音频文件的URL* @return 下载的音频文件的字节数组* @throws IOException 如果下载失败,抛出异常*/private byte[] downloadAudioFromUrl(String audioUrl) throws IOException {URL url = new URL(audioUrl);try (InputStream in = url.openStream()) {return IOUtils.toByteArray(in);}}/*** 合并两个音频文件并返回合成后的音频文件** @param audio1 录音文件* @param audio2 背景音乐url链接* @return* @throws IOException*/public File mergeAudioFiles(byte[] audio1, byte[] audio2) throws IOException {// 创建临时文件保存音频文件File audioFile1 = byteArrayToFile(audio1, "audio1_" + RandomNumberUtils.getRandomString(17, true) + ".mp3");File audioFile2 = byteArrayToFile(audio2, "audio2_" + RandomNumberUtils.getRandomString(17, true) + ".mp3");// 临时文件用于存储合并后的音频File mergedAudioFile = new File("mergedAudio_" + RandomNumberUtils.getRandomString(17, true) + ".mp3");// TODO 访问该地址复制源码: https://stjl.xyz// 将合并后的音频文件读取为字节数组并返回
// Files.readAllBytes(mergedAudioFile.toPath()); // 返回byte[]return mergedAudioFile;}
https://stjl.xyz/