📄 chap12-9.txt
字号:
// 程序12-9
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class playAudio extends JApplet {
AudioClip sound1, sound2, currentSound;
JButton playSound, loopSound, stopSound;
JComboBox choose;
public void init( ){ // 初始化各对象
Container container = getContentPane( ); // 获取内容格
container.setLayout( new FlowLayout( ) ); // 设置布局
String choices[ ] = { "Welcome", "Hi" }; // 下拉列表的选项
choose = new JComboBox( choices ); // 定义一个下拉列表
choose.addItemListener( // 定义一个匿名类,实现选择监听
new ItemListener( ) {
// 若重新选择声音文件,将停止当前播放,启动新选的声音剪辑
public void itemStateChanged( ItemEvent e ) {
currentSound.stop( ); // 停止当前播放的声音剪辑
// 确定新选的声音剪辑
currentSound = choose.getSelectedIndex( ) == 0 ? sound1 : sound2;
}
}
);
container.add( choose ); // 将组件choose加入到容器中
// 定义按钮对象,并设置事件监听者
ButtonHandler handler = new ButtonHandler( );
playSound = new JButton( "Play" );
playSound.addActionListener( handler );
container.add( playSound );
loopSound = new JButton( "Loop" );
loopSound.addActionListener( handler );
container.add( loopSound );
stopSound = new JButton( "Stop" );
stopSound.addActionListener( handler );
container.add( stopSound );
// 载入声音剪辑,并对currentSound初始化
sound1 = getAudioClip( getDocumentBase( ), "welcome.wav" );
sound2 = getAudioClip( getDocumentBase( ), "hi.au" );
currentSound = sound1;
}
// 当用户单击stop按钮时,终止播放声音剪辑
public void stop( ) {
currentSound.stop( );
}
// 定义一个内部类,处理按钮事件
private class ButtonHandler implements ActionListener {
// 处理 play,loop和stop 按钮事件
public void actionPerformed( ActionEvent actionEvent ){
if ( actionEvent.getSource( ) == playSound )
currentSound.play( );
else if ( actionEvent.getSource( ) == loopSound )
currentSound.loop( );
else if ( actionEvent.getSource( ) == stopSound )
currentSound.stop( );
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -