需求: 使用IO流將指定目錄下的若干個音頻文件的高潮部分,進行剪切,并重新拼接成一首新的音頻文件
思路(以兩首歌為例):
第一首歌有一個輸入流對象bis1。第二首歌有一個輸入流對象bis2,他們公用一條輸出流對象bos(在選擇構造方法的時候選擇含有布爾類型參數的那個),待第一首歌剪切完成后,在此基礎上追加第二首歌的“高潮部分”。
實現代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * 音樂剪切和拼接(音樂串燒) * @author * */ public class CutMusic { public static void main(String[] args) { //f1,f2分別為需要剪切的歌曲路徑 File f1 = new File( "E:\\CutMusicTest\\殘酷月光(Cover:林宥嘉).mp3" ); File f2 = new File( "E:\\CutMusicTest\\慢慢.mp3" ); //f為合并的歌曲 File f = new File( "E:\\CutMusicTest\\MergeMusic.mp3" ); cut1(f1,f2,f); } public static void cut1(File f1,File f2,File f){ BufferedInputStream bis1 = null ; BufferedInputStream bis2 = null ; BufferedOutputStream bos = null ; //第一首歌剪切部分起始字節 int start1 = 2375680 ; //320kbps(比特率)*58s*1024/8=2375680 比特率可以查看音頻屬性獲知 int end1 = 4915200 ; //320kbps*120s*1024/8=4915200 //第二首歌剪切部分起始字節,計算方式同上 int start2 = 3686400 ; int end2 = 5324800 ; int tatol1 = 0 ; int tatol2 = 0 ; try { //兩個輸入流 bis1 = new BufferedInputStream( new FileInputStream(f1)); bis2 = new BufferedInputStream( new FileInputStream(f2)); //緩沖字節輸出流(true表示可以在流的后面追加數據,而不是覆蓋?。。?/code> bos = new BufferedOutputStream( new FileOutputStream(f, true )); //第一首歌剪切、寫入 byte [] b1= new byte [ 512 ]; int len1 = 0 ; while ((len1 = bis1.read(b1))!=- 1 ){ tatol1+=len1; //累積tatol if (tatol1<start1 ){ //tatol小于起始值則跳出本次循環 continue ; } bos.write(b1); //寫入的都是在我們預先指定的字節范圍之內 if (tatol1>=end1 ){ //當tatol的值超過預先設定的范圍,則立刻刷新bos流對象,并結束循環 bos.flush(); break ; } } System.out.println( "第一首歌剪切完成!" ); //第二首歌剪切、寫入,原理同上 byte [] b2= new byte [ 512 ]; int len2 = 0 ; while ((len2 = bis2.read(b2))!=- 1 ){ tatol2 += len2; if (tatol2 < start2){ continue ; } bos.write(b2); if (tatol2>=end2){ bos.flush(); break ; } } System.out.println( "第二首歌剪切完成!" ); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { //切記要關閉流??! if (bis1!= null ) bis1.close(); if (bis2!= null ) bis2.close(); if (bos!= null ) bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |
獲取音頻文件比特率的方式:
運行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。