Carregando e tocando um arquivo de áudio em um applet

Esta dica mostra um método para carregar e tocar um arquivo de áudio em um applet. Uma coisa interessante que você pode fazer com essa dica é tentar criar o seu próprio tocador de músicas.

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

public class LoadAudioAndPlay extends JApplet {
   private AudioClip sound1, sound2, currentSound;  
   private JButton playSound, loopSound, stopSound;
   private JComboBox chooseSound;

   //Carrega a imagem quando o applet é iniciado
   public void init()
   {
      Container c = getContentPane();
      c.setLayout( new FlowLayout() );

      String choices[] = { "Welcome""Hi" };
      chooseSound = new JComboBox( choices );
      chooseSound.addItemListener(
         new ItemListener() {
            public void itemStateChanged( ItemEvent e )
            {
               currentSound.stop();

               currentSound =
                  chooseSound.getSelectedIndex() == ?
                     sound1 : sound2;
            }
         }
      );
      c.add( chooseSound );

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

      sound1 = getAudioClip(
                 getDocumentBase(), "inicio.wav" );
      sound2 = getAudioClip(
                 getDocumentBase(), "hi.au" );
      currentSound = sound1;
   }

   // para a música quando o usuário troca de página
   public void stop()
   {
      currentSound.stop();
   }

   private class ButtonHandler implements ActionListener {
      public void actionPerformed( ActionEvent e )
      {
         if ( e.getSource() == playSound ) c
            currentSound.play();
         else if ( e.getSource() == loopSound ) 
            currentSound.loop();
         else if ( e.getSource() == stopSound ) 
            currentSound.stop();
      }
   }
}