扫雷游戏制作全过程04 添加音乐

好像偏离主题已经有两天了。不过为了增加游戏的趣味性,音乐是一定要有的。(使用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();
	}
}
需要注意的事项我已经在注释里写了。下一次博客,我们继续开始扫雷剧情的主路线!

代码及音乐资源已经上传。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章