音樂格式轉換:java程式碼實現

_titleInfo發表於2024-05-12
 1 package util;
 2 
 3 import ws.schild.jave.*;
 4 import java.io.File;
 5 
 6 /*
 7 音樂格式轉換
 8  <dependency>
 9     <groupId>ws.schild</groupId>
10     <artifactId>jave-core</artifactId>
11     <version>2.4.4</version>
12 </dependency>
13 <dependency>-->
14     <groupId>ws.schild</groupId>-->
15     <artifactId>jave-native-win64</artifactId>-->
16     <version>2.4.4</version>-->
17 </dependency>-->
18  */
19 public class musicFactoryChange {
20     // 將文basicDir資料夾下的檔案都轉為dstFormat格式
21     public static void audioFormatConversion(String basicDir,String dstFormat){
22         AudioAttributes audio = new AudioAttributes();
23         if(dstFormat.equals("wav")) {
24             audio.setCodec("pcm_s16le");
25         }else if(dstFormat.equals("mp3")) {
26             audio.setCodec("libmp3lame");
27         }else if(dstFormat.equals("amr")){
28             audio.setCodec("libvo_amrwbenc");
29         }
30         audio.setBitRate(16000);
31         audio.setChannels(1);
32         audio.setSamplingRate(16000);
33         //Encoding attributes
34         EncodingAttributes attrs = new EncodingAttributes();
35         attrs.setFormat(dstFormat);
36         attrs.setAudioAttributes(audio);
37 
38         File dir = new File(basicDir);
39         String[] files= dir.list();
40         // 將輸出都儲存在basicDir\\output\\下
41         if(files != null){
42             File dstDir = new File(basicDir+"output");
43             dstDir.mkdir();
44         }
45 
46         int cnt = 0;
47         for(String fileName:files){
48             // 跳過資料夾,只處理檔案
49             if(new File(basicDir+fileName).isDirectory()){
50                 continue;
51             }
52             // 擷取"xxx.amr"小數點前的所有字串
53             String[] substrs = fileName.split("\\.");
54             String substr = substrs[0];
55 
56             // 定義輸入的檔案和輸出的檔案
57             File sourceFile = new File(basicDir+fileName);
58             File targetFile = new File(basicDir+"output\\"+substr+"."+dstFormat);
59 
60             // 編碼格式轉換
61             try {
62                 Encoder encoder = new Encoder();
63                 encoder.encode(new MultimediaObject(sourceFile), targetFile, attrs);
64             }catch (Exception e){
65                 System.out.println("err,fileName: "+sourceFile);
66                 e.printStackTrace();
67             }
68             System.out.println("suc,sourceFile: "+sourceFile);
69             System.out.println("suc, : "+ ++cnt);
70         }
71     }
72 
73     public static void main(String[] args){
74         audioFormatConversion("F:\\afile\\","mp3");
75     }
76 
77 }

相關文章