使用有道api抓取读音

转载请表明出处 https://blog.csdn.net/Amor_Leo/article/details/106843484 谢谢

使用有道api抓取读音

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;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值