【Java音频操作】调用有道词典语音接口,生成单词MP3文件,支持自定义重复次数
參考博客:Java爬蟲-爬取四級(jí)詞匯網(wǎng)站音頻
運(yùn)行效果
根據(jù)想要拼接的單詞,生成一個(gè)單詞朗讀的mp3文件,可以自定義每個(gè)單詞朗讀時(shí)的重復(fù)次數(shù)。
代碼思路:
- 先把要拼接的單詞放進(jìn)一個(gè)String數(shù)組中
- 然后遍歷這個(gè)數(shù)組,用(偽)爬蟲下載每一個(gè)單詞的音頻文件
- 最后再把這些音頻文件拼接起來(lái),生成mp3文件 ↓
關(guān)于:有道詞典語(yǔ)音接口
基于有道翻譯的公共api可以制作自己的翻譯app,前幾天有這個(gè)想法,發(fā)現(xiàn)沒(méi)有辦法實(shí)現(xiàn)朗讀功能,搜索了一下找到了這個(gè)接口,解決了這個(gè)問(wèn)題。非常簡(jiǎn)單,直接取網(wǎng)絡(luò)地址進(jìn)行播放就可以了,相當(dāng)于播放一個(gè)音頻文件,解析速度挺快。
美音:http://dict.youdao.com/dictvoice?type=0&audio=hello 英音:http://dict.youdao.com/dictvoice?type=1&audio=helloapi僅有兩個(gè)參數(shù),就是發(fā)音類型和單詞,在audio=后面加上單詞就ok了,type=0為美國(guó)發(fā)音,type=1為英國(guó)發(fā)音,做個(gè)程序自己用,幾乎還可以吧。下面附上一個(gè)"hello"的測(cè)試,看下效果吧,第一個(gè)為美音,第二個(gè)為英音
關(guān)于:java播放mp3格式音頻文件
1、下載第三方j(luò)ar包,網(wǎng)址:http://www.javazoom.net/javalayer/javalayer.html
2、下載完成之后解壓提取jl1.0.0.1.jar
3、在eclipse的Java Build Path中添加jl1.0.0.1.jar
4、播放MP3文件的源代碼(參考使用)
關(guān)于:從四級(jí)聽(tīng)力網(wǎng)站上下載MP3的代碼(參考使用)
主程序類
package top.chen.dogwood;import java.io.IOException; import java.net.MalformedURLException;/*** 爬取指定鏈接的一組MP3 文件* * 放入指定的目錄中* * @author Geek* */ public class Application {public static void main(String[] args) throws MalformedURLException,IOException {String base = "http://download.dogwood.com.cn/online/4jlxbx/";String[] strings = new String[35] ;for (int i = 1; i <= 35; i++) {strings[i-1] = base+String.format("%02d", i)+".mp3";}DownloadUtils downloadUtils = new DownloadUtils(strings,"mp3","E:\\360Downloads\\TempFile");try {downloadUtils.httpDownload();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}} }下載工具類
package top.chen.dogwood;import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;public class DownloadUtils {// 目標(biāo)鏈接字符串private String[] urlString;// 目標(biāo)文件的格式private String targetType;// 存放文件路徑private File rootDir;public String[] getUrlString() {return urlString;}public void setUrlString(String[] urlString) {this.urlString = urlString;}public String getTargetType() {return targetType;}public void setTargetType(String targetType) {this.targetType = targetType;}public File getRootDir() {return rootDir;}public void setRootDir(File rootDir) {this.rootDir = rootDir;}public DownloadUtils(String[] urlString, String targetType, File rootDir) {super();this.urlString = urlString;this.targetType = targetType;this.rootDir = rootDir;}public DownloadUtils(String[] urlString, String targetType, String rootDir) {super();this.urlString = urlString;this.targetType = targetType;this.rootDir = new File(rootDir);}public DownloadUtils() {super();}/*** 開(kāi)始下載* * @throws Exception*/public void httpDownload() throws Exception {validate();final String[] urls = urlString;HttpURLConnection urlConnection;for (int i = 0; i < urls.length; i++) {urlConnection = (HttpURLConnection) new URL(urls[i]).openConnection();// 開(kāi)啟鏈接urlConnection.connect();InputStream inputStream = urlConnection.getInputStream();File temp = new File(rootDir,String.format("%02d",i+1)+"."+targetType);if (!temp.exists()) {temp.createNewFile();}FileOutputStream fileOutputStream = new FileOutputStream(temp, true);int tem;while (-1 != (tem = inputStream.read())) {fileOutputStream.write(tem);fileOutputStream.flush();}fileOutputStream.close();inputStream.close();}}private void validate() throws Exception {if (urlString.length <= 0) {throw new Exception("下載路徑不能為空!");}if (null == rootDir || !rootDir.exists() || !rootDir.isDirectory()) {throw new Exception("目標(biāo)文件夾不存在!");}}}不過(guò)單線程下載速度有點(diǎn)慢 ,以后有空考慮下改成多線程下載
關(guān)于:文件的拼接(未使用,僅參考)
import java.io.*; public class D3 {public static void main(String[] args) throws Exception {BufferedOutputStream buff=new BufferedOutputStream(new FileOutputStream("D:\\zuoye/text.mp3"));FileInputStream int1=new FileInputStream("D:\\zuoye/太田美知彥 - 萬(wàn)里の長(zhǎng)城.mp3");FileInputStream int2=new FileInputStream("D:\\zuoye/阿桑 - 寂寞在唱歌.mp3");//FileInputStream int3=new FileInputStream("D:\\zuoye/r.mp3");BufferedInputStream but1=new BufferedInputStream(int1);BufferedInputStream but2=new BufferedInputStream(int2);//BufferedInputStream but3=new BufferedInputStream(int3);SequenceInputStream seq1=new SequenceInputStream(but1, but2);//將兩首歌合在一起 //SequenceInputStream seq2=new SequenceInputStream(seq1, but3);//將三首歌合在一起 int i;while((i=seq1.read())!=-1) {buff.write(i);}buff.close();seq1.close();//seq1.close();but2.close();} }本程序完整代碼(下載+拼接MP3)
GLOBAL.java
package cn.hanquan.music;import java.io.File;public class GLOBAL {/*-----------------------------------自定義begin-----------------------------------*/// 填寫單詞public static String sentence = new String("furnish establish qualification apply terrific thrill allegiance freelance objection substantial interpret fraction denote fruitful inlet lame pinch remnant projector torrent incident zeal overlook shear propaganda prescribe cape");//public static String sentence = new String("apply furnish establish qualification apply terrific");public static String[] words = sentence.split(" "); // 分隔符號(hào)// 存放路徑public static File rootDir = new File("C:\\mywords"); // 存放文件路徑// 接口來(lái)源public static String baseAPI=new String("http://dict.youdao.com/dictvoice?type=0&audio=");//t=1英音 t=0美英音 (建議t=1)// 組合public static boolean BIND = true; // 是否組合public static String BINDNAME = "wordlist1"; // 組合文件名public static int REPEAT = 2; // 組合重復(fù)次數(shù)/*-----------------------------------自定義end-----------------------------------*/// 文件格式(勿動(dòng))public static String targetType = "mp3";// 目標(biāo)文件的格式// 完整音頻url(勿動(dòng))public static String[] wordsUrl = new String[GLOBAL.words.length];// 目標(biāo)鏈接字符串}MusicPlay.java
package cn.hanquan.music;import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL;import javazoom.jl.decoder.JavaLayerException; import javazoom.jl.player.*;/** ----------單詞播放器----------* 自定義內(nèi)容的定義在GLOBAL.java中,自行修改。* * 未解決:當(dāng)網(wǎng)址中t=0美音時(shí),重復(fù)單詞順序混亂,有的單詞被跳過(guò)。考慮坑能是寫文件操作時(shí),上一個(gè)文件沒(méi)有寫完,就直接寫寫一個(gè)導(dǎo)致?* 計(jì)劃解決方式:每一次重新打開(kāi)文件、關(guān)閉文件。*/ public class MusicPlay {static Player player;File music;public static void main(String[] args) throws MalformedURLException, IOException, JavaLayerException {//get words urlfor (int i = 0; i < GLOBAL.words.length; i++) {GLOBAL.wordsUrl[i] = new String(GLOBAL.baseAPI + GLOBAL.words[i]);}//downloadDownloadUtils downloadUtils = new DownloadUtils();try {downloadUtils.httpDownload();} catch (Exception e) {e.printStackTrace();}//playif (GLOBAL.BIND) {// bindplay(GLOBAL.BINDNAME);} else {// not bindfor (int i = 0; i < GLOBAL.words.length; i++) {System.out.println("播放" + GLOBAL.words[i]);play(GLOBAL.words[i]);}}}// play functionpublic static void play(String str) throws FileNotFoundException, JavaLayerException {BufferedInputStream buffer = new BufferedInputStream(new FileInputStream("C:\\mywords\\" + str + ".mp3"));player = new Player(buffer);player.play();} }class DownloadUtils {// 開(kāi)始下載public void httpDownload() throws Exception {validate();// checkHttpURLConnection urlConnection;for (int i = 0; i < GLOBAL.wordsUrl.length; i++) {int r = GLOBAL.REPEAT;while (r > 0) {String word = (String) GLOBAL.wordsUrl[i].subSequence(GLOBAL.wordsUrl[i].lastIndexOf("=") + 1,GLOBAL.wordsUrl[i].length());urlConnection = (HttpURLConnection) new URL(GLOBAL.wordsUrl[i]).openConnection();urlConnection.connect();InputStream inputStream = urlConnection.getInputStream();if (GLOBAL.BIND) {// bindFile temp = new File(GLOBAL.rootDir, GLOBAL.BINDNAME + "." + GLOBAL.targetType);// 合一起if (!temp.exists()) {temp.createNewFile();}FileOutputStream fileOutputStream = new FileOutputStream(temp, true);int t;while (-1 != (t = inputStream.read())) {fileOutputStream.write(t);fileOutputStream.flush();}fileOutputStream.close();inputStream.close();System.out.println(word + "下載成功");} else {// not bindFile temp = new File(GLOBAL.rootDir, word + "." + GLOBAL.targetType);// 分開(kāi)if (!temp.exists()) {temp.createNewFile();FileOutputStream fileOutputStream = new FileOutputStream(temp, true);int tem;while (-1 != (tem = inputStream.read())) {fileOutputStream.write(tem);fileOutputStream.flush();}fileOutputStream.close();inputStream.close();System.out.println(word + "下載成功");} else {System.out.println(word + "重復(fù)");}}r--;}}}private void validate() throws Exception {if (GLOBAL.wordsUrl.length <= 0) {throw new Exception("下載路徑不能為空!");}if (null == GLOBAL.rootDir || !GLOBAL.rootDir.exists() || !GLOBAL.rootDir.isDirectory()) {throw new Exception("目標(biāo)文件夾不存在!");}} }運(yùn)行效果
eclipse控制臺(tái)輸出
生成的mp3文件
總結(jié)
以上是生活随笔為你收集整理的【Java音频操作】调用有道词典语音接口,生成单词MP3文件,支持自定义重复次数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【PAT甲级 TreeMap的使用】10
- 下一篇: 【Java】利用容器存储表格数据