import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AudioPlayer extends JApplet {
  private AudioClip[] sounds;
  private AudioClip currentSound;
  private JButton playSound, loopSound, stopSound;
  private JComboBox<String> chooseSound;

  public AudioPlayer(){
    String choices[] = { "happyface.wav","moonriver.wav","horse.mid","eagle.wav"};
     
    setLayout(new FlowLayout());
    chooseSound = new JComboBox<String>( choices );
    chooseSound.addItemListener(
    new ItemListener() {
      public void itemStateChanged( ItemEvent e ){
        currentSound.stop();
        currentSound=sounds[chooseSound.getSelectedIndex()];
      }
    });
    add( chooseSound );

    ButtonHandler handler = new ButtonHandler();
    playSound = new JButton( "Play" );
    playSound.addActionListener( handler );
    add( playSound );
    loopSound = new JButton( "Loop" );
    loopSound.addActionListener( handler );
    add( loopSound );
    stopSound = new JButton( "Stop" );
    stopSound.addActionListener( handler );
    add( stopSound );

    sounds=new AudioClip[choices.length];
    for(int i=0;i<choices.length;i++)
      sounds[i]= newAudioClip(getClass().getResource(choices[i] ));
  
    currentSound=sounds[0];
  }

  private class ButtonHandler implements ActionListener {
    public void actionPerformed( ActionEvent e ){
      if ( e.getSource() == playSound )
        currentSound.play();
      else if ( e.getSource() == loopSound )
        currentSound.loop();
      else if ( e.getSource() == stopSound )
        currentSound.stop();
    }
  }
   
  public static void main(String args[]){
    JFrame gui=new JFrame("音乐播放器");
    AudioPlayer player=new AudioPlayer();
    gui.setContentPane(player);
    gui.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    gui.setSize(400,100);
    gui.setVisible( true );
  }
}


/****************************************************
 * 作者：孙卫琴                                     *
 * 来源：<<Java面向对象编程>>                       *
 * 技术支持网址：www.javathinker.net                *
 ***************************************************/
