// File: SoundApp.java
// T Balls : Jan 2000
// Sound Application to demonstrate Java-2
// sound capabilities
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
import java.io.*;
import java.net.*;
public class SoundApp extends JFrame
{ public SoundApp()
{ setTitle( "Sound Application" );
JMenuBar mb = new JMenuBar();
this.setJMenuBar( mb );
JMenu f = new JMenu( "File" );
mb.add( f );
JMenuItem open = new JMenuItem( "Open" );
open.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{ getFile();
SoundApp.this.repaint(); // messy!
}
});
JMenuItem exit = new JMenuItem( "Exit" );
exit.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{ dispose();
System.exit(0);
}
});
f.add( open );
f.add( new JSeparator() );
f.add( exit );
this.getContentPane().add( url, BorderLayout.NORTH );
url.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e )
{ getAudioClip();
}
});
JPanel buttons = new JPanel();
this.getContentPane().add( buttons, BorderLayout.SOUTH );
JButton play = new JButton( "Play" );
play.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e )
{ if( clip != null );
clip.play();
}
});
buttons.add( play );
JButton loop = new JButton( "Loop" );
loop.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e )
{ if( clip != null );
clip.loop();
}
});
buttons.add( loop );
JButton stop = new JButton( "Stop" );
stop.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e )
{ if( clip != null );
clip.stop();
}
});
buttons.add( stop );
this.addWindowListener( new WindowAdapter(){
public void windowClosing(WindowEvent e)
{ dispose();
System.exit(0);
}
});
}
private JTextField url = new JTextField();
private AudioClip clip = null;
private File file = null;
private void getFile()
{ JFileChooser fc = new JFileChooser( new File( "." ) );
fc.setDialogType( JFileChooser.OPEN_DIALOG );
fc.setDialogTitle( "Choose a sound file: " );
int result = fc.showOpenDialog( this );
if( result == JFileChooser.CANCEL_OPTION )
{ file = null;
}
else
{ file = fc.getSelectedFile();
}
url.setText( "file:./" + file.getName() );
getAudioClip();
}
// Use text in url to load the clip
private void getAudioClip()
{ try
{ clip = Applet.newAudioClip( new URL( url.getText() ) );
}
catch( Exception e )
{ e.printStackTrace();
clip = null;
}
}
public static void main(String args[])
{
System.out.println("Starting Sound Application");
SoundApp f = new SoundApp();
f.pack();
f.setVisible( true );
}
} |