好像偏離主題已經有兩天了。不過爲了增加遊戲的趣味性,音樂是一定要有的。(使用JMF當然可以,但是簡簡單單的JDK中自帶的AudioClip就沒問題了)
該類一共有3個方法:play,loop,stop。
具體的應用非常之簡單,但是它支持的格式很少,只支持wav和au。
import java.awt.*;
import javax.swing.*;
import java.applet.*;
import java.net.*;
import java.awt.event.*;
public class PlayMusic extends JFrame implements ActionListener
{
private JButton jb1 = new JButton("play");
private JButton jb2 = new JButton("loop");
private JButton jb3 = new JButton("stop");
private JButton jb4 = new JButton("play");
private JButton jb5 = new JButton("stop");
//第一步
private AudioClip music = null, song = null;
public PlayMusic()
{
super("music");
try
{
/*這個應該是定位了文件的絕對地址,我試了一下,用相對地址也OK
*但是要有"file:"
String sep = System.getProperty("file.separator");
String preface = "file:"+System.getProperty("user.dir")
+sep; //+"Audio"+sep;
music = Applet.newAudioClip(new URL(preface+"a.wav"));
song = Applet.newAudioClip(new URL(preface+"b.wav"));
*/
music = Applet.newAudioClip(new URL("file:a.wav"));
song = Applet.newAudioClip(new URL("file:b.wav"));
}catch(Exception e){}
Container content =getContentPane();
content.setLayout(new FlowLayout());
content.add(jb1);jb1.addActionListener(this);
content.add(jb2);jb2.addActionListener(this);
content.add(jb3);jb3.addActionListener(this);
content.add(jb4);jb4.addActionListener(this);
content.add(jb5);jb5.addActionListener(this);
validate(); pack();setVisible(true);
}
public static void main(String []args)
{
PlayMusic t = new PlayMusic();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == jb1)
music.play();
else if(e.getSource() == jb2)
music.loop();
else if(e.getSource() == jb3)
music.stop();
else if(e.getSource() == jb4)
song.play();
else if(e.getSource() == jb5)
song.stop();
}
}
需要注意的事項我已經在註釋裏寫了。下一次博客,我們繼續開始掃雷劇情的主路線!
代碼及音樂資源已經上傳。