學習過java語言的你,或多或少,在某天突發(fā)奇想,想著用swing做一個音樂播放器。但是,發(fā)現(xiàn)很難找到,相關(guān)的java代碼,或者你下載的代碼有問題,或者你代碼里面引入的類包找不到。為了解決自如此類的問題。在這兒,有如下的代碼可以供大家參考。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package TheMusic; import java.io.*; import javax.sound.sampled.*; public class Music { public static void main(String[] args) { // TODO Auto-generated method stub //修改你的音樂文件路徑就OK了 AePlayWave apw= new AePlayWave( "突然好想你.wav" ); apw.start(); } } |
在程序中實例化這個類,啟動線程,實例化的時候參照Test修改路徑就OK播放聲音的類
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
|
public class AePlayWave extends Thread { private String filename; public AePlayWave(String wavfile) { filename = wavfile; } public void run() { File soundFile = new File(filename); AudioInputStream audioInputStream = null ; try { audioInputStream = AudioSystem.getAudioInputStream(soundFile); } catch (Exception e1) { e1.printStackTrace(); return ; } AudioFormat format = audioInputStream.getFormat(); SourceDataLine auline = null ; DataLine.Info info = new DataLine.Info(SourceDataLine. class , format); try { auline = (SourceDataLine) AudioSystem.getLine(info); auline.open(format); } catch (Exception e) { e.printStackTrace(); return ; } auline.start(); int nBytesRead = 0 ; byte [] abData = new byte [ 512 ]; try { while (nBytesRead != - 1 ) { nBytesRead = audioInputStream.read(abData, 0 , abData.length); if (nBytesRead >= 0 ) auline.write(abData, 0 , nBytesRead); } } catch (IOException e) { e.printStackTrace(); return ; } finally { auline.drain(); auline.close(); } } } |
好了,到此結(jié)束。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。