转载请表明出处 https://blog.youkuaiyun.com/Amor_Leo/article/details/106843484 谢谢
pom
<!-- file转换文件流-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
</dependency>
yml
youdao:
downPath: D:/temp/down
工具类
/**
* 抓取读音并上传文件服务器工具类
*
* @author LHL
*/
@Slf4j
@Component
public class WordVoiceUtil {
@Value("${youdao.downPath}")
private String downPath;
/**
* 抓取音频并上传oss
*
* @param content 要抓取读音的内容
* @return String
*/
public String getVoiceLink(String content) {
String query = content.toLowerCase().trim();
try {
query = URLEncoder.encode(query,"utf-8");
} catch (UnsupportedEncodingException e) {
log.info("抓取读音 \t 内容encode失败: {}", query);
e.printStackTrace();
}
// 0美 1英
String speechUrl = "https://dict.youdao.com/dictvoice?type=1&audio=" + query;
log.info("抓取读音 \t 抓取地址: {}", speechUrl);
String fileUpload = null;
File dir = new File(downPath);
//创建文件夹
if (!dir.exists()) {
dir.mkdir();
}
String path = downPath + "/" + StrUtil.createFileNameUseTime() + ".mp3";
log.info("抓取读音 \t 临时下载本地地址: {}", path);
URL url = null;
InputStream is = null;
OutputStream os = null;
FileInputStream fileInputStream = null;
File audio = null;
try {
url = new URL(speechUrl);
is = new BufferedInputStream(url.openStream());
os = new FileOutputStream(path);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
//buffer数组存放读取的字节,如果因为流位于文件末尾而没有可用的字节,则返回值-1,以整数形式返回实际读取的字节数
os.write(buffer, 0, bytesRead);
}
audio = new File(path);
if (audio.exists()) {
log.info("抓取读音 \t 临时下载本地,下载成功");
fileInputStream = new FileInputStream(audio);
MultipartFile multipartFile = new MockMultipartFile(audio.getName(), audio.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
fileUpload = FileUploadOssUtil.fileUpload(multipartFile); //上传到文件服务器 看自己的项目用的什么
log.info("抓取读音 \t 上传oss文件路径: {}", fileUpload);
}
} catch (IOException e) {
e.printStackTrace();
log.error("抓取读音 \t 下载失败");
} finally {
if (os != null) {
try {
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != audio) {
if (audio.exists()) {
audio.delete();
log.info("抓取读音 \t 删除临时下载到本地的文件: {}", path);
}
}
}
return fileUpload;
}
}