1、先上素材。【键盘图片×1,wav音符×13】
链接:https://pan.baidu.com/s/1yw2-1OXDZQylzaEtD685UA
提取码:fzks
2、简述题目及思路。
今实验,遇一题,求绘制图形,添加按钮,可弹奏。
思路:采用Applet 技术绘制图形,多线程的技术输出播放奏曲子。
3、分析代码、上代码。
public class Demo04 extends Applet{
// 键盘图片
Image keyBoard = null;
// 加载所有13个音符资源
AudioClip[] notes1 = new AudioClip[7]; // a1 - g1
AudioClip[] notes2 = new AudioClip[6];
// 按钮
Button[] btns = new Button[17];
public void init() {
keyBoard = getImage(getCodeBase(),"keyBoard.jpg");
// 加载音频,因格式不齐,所以采用分支循环语句进行限制
for (int i = 0; i < 7; i++) {
notes1[i] = getAudioClip(getCodeBase(), ""+(char)(i+'a')+"1.wav");
}
char ch;
int j = 0;
for (int i = 0; i < 7; i++) {
ch = (char)(i+'a');
if(ch=='a'||ch=='c'||ch=='d'||ch=='f'||ch=='g') {
notes2[j++] = getAudioClip(getCodeBase(), ch+"1s.wav");
}
}
notes2[5] = getAudioClip(getCodeBase(),"c2.wav");
}
public void paint(Graphics g) {
g.drawImage(keyBoard, 40, 40, 550, 200,this);
}
@Override
public void start() {
this.setLayout(null);
int r,g,b;
// 初始化按钮:定位+颜色+大小
for (int i = 0; i < 17; i++) {
btns[i]= new Button(""+(char)('a'+i));
r= (int)(Math.random()*255);
g= (int)(Math.random()*255);
b= (int)(Math.random()*255);
btns[i].setBackground(new Color(r, g, b,125));
btns[i].setSize(32, 120);
btns[i].setLocation(i*32+42, 42);
add(btns[i]);
}
// 添加监听器
for (int i = 0; i < 17; i++) {
btns[i].addKeyListener(new myKeyHandler());
btns[i].addActionListener(new myActionHandler());
}
}
// 处理按键事件 => 采用多线程方法播放
class myKeyHandler extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e) {
int index = e.getKeyChar()-'a';
if(index < 0 || index > 16)
return;
if(index < 7) {
new myNoteThread(notes1[index]).start();
}else if(index < 13) {
new myNoteThread(notes1[index-7]).start();
}else {
new myNoteThread(notes1[index-13]).start();
}
System.out.println(Thread.activeCount());
}
}
// 处理鼠标点击事件 => 采用多线程方法播放
class myActionHandler implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) {
Button btn = (Button) e.getSource();
int index = (char)(btn.getActionCommand().toCharArray()[0]-'a'); // 0-16
if(index < 7) {
new myNoteThread(notes1[index]).start();
}else if(index < 13) {
new myNoteThread(notes1[index-7]).start();
}else {
new myNoteThread(notes1[index-13]).start();
}
System.out.println(Thread.activeCount());
}
}
@Override
public void stop() {
// 关闭所有音乐
for (int i = 0; i < 7; i++) {
if(i < 6)
notes2[i].stop();
notes1[i].stop();
}
}
}
// Thread类重写
class myNoteThread extends Thread
{
AudioClip clip;
public myNoteThread(AudioClip cp) {
clip = cp;
}
@Override
public void run() {
clip.play();
}
}