JavaSE系列代码66:在小程序里播放音乐

To trigger a new thread, use the start () method, such as: Mythread t = new Mythread (); t.start (); when the start () method is called, a new control thread is created, and then it calls the run () method. The code in the § run() method defines the functions required to execute the thread.

import java.awt.*; 
import java.awt.event.*;
import java.applet.Applet;
import java.applet.AudioClip;
public class Javase_66 extends Applet implements ItemListener
{
  AudioClip[] midi=new AudioClip[3]; //定义AudioClip接口类型的数组
  AudioClip song;                    //目前选取的音乐
  Choice coi=new Choice();           //创建下拉列表对象
  Button bnt_loop=new Button("循环");
  Button bnt_stop=new Button("停止");
  public void init()
  {
    String num;
    for(int i=0;i<midi.length;i++)
    {
      num=String.valueOf(i+1);
      midi[i]=getAudioClip(getCodeBase(),num+".mid");//取得音乐来源
    }
    coi.add("us");  coi.add("us"); coi.add("us");
    add(coi);   
    add(bnt_loop); add(bnt_stop);
    coi.addItemListener(this);   //将小程序本身设置为coi的监听者
    bnt_loop.addActionListener(new MyActLit());  //设置监听者
    bnt_stop.addActionListener(new MyActLit());  
    song=midi[0];     //设置启动小程序时播放的音乐
    song.play();      //播放音乐
  }
  public void itemStateChanged(ItemEvent e)
  {
    song.stop();       //停止正在播放的音乐
    int i=coi.getSelectedIndex();  //在下拉列表中选择播放音乐的序号
    song=midi[i];                  //设置待播放的音乐
    song.play();                   //播放音乐
  }
  class MyActLit implements ActionListener  //定义内部类
  {
     public void actionPerformed(ActionEvent e)  //处理按钮事件的程序代码
     {
        Button bnt=(Button) e.getSource();   //取得被选中的按钮
        if (bnt==bnt_loop) song.loop();  //若选择“循环”按钮,则循环播放
        else song.stop();              //若选择“停止”按钮,则停止播放
    }
  }
}
相应的HTML文件如下:
<Javase_66 .html>
<html>
<applet code="Javase_66 .class"
        width=300
        height=100 >
</applet>
</html>
发布了73 篇原创文章 · 获赞 189 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/blog_programb/article/details/105568873