【Java音频操作】调用有道词典语音接口,生成单词MP3文件,支持自定义重复次数
生活随笔
收集整理的這篇文章主要介紹了
【Java音频操作】调用有道词典语音接口,生成单词MP3文件,支持自定义重复次数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
參考博客:Java爬蟲-爬取四級詞匯網站音頻
運行效果
根據想要拼接的單詞,生成一個單詞朗讀的mp3文件,可以自定義每個單詞朗讀時的重復次數。
代碼思路:
- 先把要拼接的單詞放進一個String數組中
- 然后遍歷這個數組,用(偽)爬蟲下載每一個單詞的音頻文件
- 最后再把這些音頻文件拼接起來,生成mp3文件 ↓
關于:有道詞典語音接口
基于有道翻譯的公共api可以制作自己的翻譯app,前幾天有這個想法,發現沒有辦法實現朗讀功能,搜索了一下找到了這個接口,解決了這個問題。非常簡單,直接取網絡地址進行播放就可以了,相當于播放一個音頻文件,解析速度挺快。
美音:http://dict.youdao.com/dictvoice?type=0&audio=hello 英音:http://dict.youdao.com/dictvoice?type=1&audio=helloapi僅有兩個參數,就是發音類型和單詞,在audio=后面加上單詞就ok了,type=0為美國發音,type=1為英國發音,做個程序自己用,幾乎還可以吧。下面附上一個"hello"的測試,看下效果吧,第一個為美音,第二個為英音
關于:java播放mp3格式音頻文件
1、下載第三方jar包,網址: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文件的源代碼(參考使用)
關于:從四級聽力網站上下載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 {// 目標鏈接字符串private String[] urlString;// 目標文件的格式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();}/*** 開始下載* * @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();// 開啟鏈接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("目標文件夾不存在!");}}}不過單線程下載速度有點慢 ,以后有空考慮下改成多線程下載
關于:文件的拼接(未使用,僅參考)
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/太田美知彥 - 萬里の長城.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(" "); // 分隔符號// 存放路徑public static File rootDir = new File("C:\\mywords"); // 存放文件路徑// 接口來源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; // 組合重復次數/*-----------------------------------自定義end-----------------------------------*/// 文件格式(勿動)public static String targetType = "mp3";// 目標文件的格式// 完整音頻url(勿動)public static String[] wordsUrl = new String[GLOBAL.words.length];// 目標鏈接字符串}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.*;/** ----------單詞播放器----------* 自定義內容的定義在GLOBAL.java中,自行修改。* * 未解決:當網址中t=0美音時,重復單詞順序混亂,有的單詞被跳過??紤]坑能是寫文件操作時,上一個文件沒有寫完,就直接寫寫一個導致?* 計劃解決方式:每一次重新打開文件、關閉文件。*/ 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 {// 開始下載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);// 分開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 + "重復");}}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("目標文件夾不存在!");}} }運行效果
eclipse控制臺輸出
生成的mp3文件
總結
以上是生活随笔為你收集整理的【Java音频操作】调用有道词典语音接口,生成单词MP3文件,支持自定义重复次数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【PAT甲级 TreeMap的使用】10
- 下一篇: 【Java】利用容器存储表格数据