需求: 使用IO流將指定目錄下的若干個(gè)音頻文件的高潮部分,進(jìn)行剪切,并重新拼接成一首新的音頻文件
思路(以兩首歌為例):
第一首歌有一個(gè)輸入流對(duì)象bis1。第二首歌有一個(gè)輸入流對(duì)象bis2,他們公用一條輸出流對(duì)象bos(在選擇構(gòu)造方法的時(shí)候選擇含有布爾類型參數(shù)的那個(gè)),待第一首歌剪切完成后,在此基礎(chǔ)上追加第二首歌的“高潮部分”。
實(shí)現(xiàn)代碼:
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 ; //第一首歌剪切部分起始字節(jié) int start1 = 2375680 ; //320kbps(比特率)*58s*1024/8=2375680 比特率可以查看音頻屬性獲知 int end1 = 4915200 ; //320kbps*120s*1024/8=4915200 //第二首歌剪切部分起始字節(jié),計(jì)算方式同上 int start2 = 3686400 ; int end2 = 5324800 ; int tatol1 = 0 ; int tatol2 = 0 ; try { //兩個(gè)輸入流 bis1 = new BufferedInputStream( new FileInputStream(f1)); bis2 = new BufferedInputStream( new FileInputStream(f2)); //緩沖字節(jié)輸出流(true表示可以在流的后面追加數(shù)據(jù),而不是覆蓋!!) 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小于起始值則跳出本次循環(huán) continue ; } bos.write(b1); //寫入的都是在我們預(yù)先指定的字節(jié)范圍之內(nèi) if (tatol1>=end1 ){ //當(dāng)tatol的值超過預(yù)先設(shè)定的范圍,則立刻刷新bos流對(duì)象,并結(jié)束循環(huán) 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 { //切記要關(guān)閉流!! 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(); } } } } |
獲取音頻文件比特率的方式:
運(yùn)行結(jié)果:
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。