轉載請表明出處 https://blog.csdn.net/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();
}
String speechUrl = "https://dict.youdao.com/dictvoice?type=2&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;
}
}