播放音頻——音頻播放程序

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JButton;

import javax.swing.JFrame;
public class AudioPlayDemo extends JFrame{
	private AudioClip audioClip; 
	 public AudioPlayDemo() {
		 super();
	        getContentPane().setLayout(null);
	        setTitle("音頻播放程序");
	        setBounds(100, 100, 331, 192);
	        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	        final JButton btn_play = new JButton();
	        btn_play.addActionListener(new ActionListener() {
	            public void actionPerformed(final ActionEvent arg0) {
	                URL url = null;  // 定義音頻文件的RUL
	                try {
	                    url = new File("E:/music/mid.mid").toURI().toURL();// 得到URL對象
	                    if (audioClip != null)
	                        audioClip.stop();  // 中止播放
	                    audioClip = Applet.newAudioClip(url);// 獲取音頻剪輯對象
	                    audioClip.play();   // 播放音頻
	                } catch (MalformedURLException e) {
	                    e.printStackTrace();
	                }
	                
	            }
	        });
	        btn_play.setText("播    放");
	        btn_play.setBounds(22, 60, 80, 28);
	        getContentPane().add(btn_play);
	        
	        final JButton btn_stop = new JButton();
	        btn_stop.addActionListener(new ActionListener() {
	            public void actionPerformed(final ActionEvent arg0) {
	                if (audioClip != null)
	                    audioClip.stop();   // 中止播放
	            }
	        });
	        btn_stop.setText("停    止");
	        btn_stop.setBounds(115, 60, 80, 28);
	        getContentPane().add(btn_stop);
	        
	        final JButton btn_loop = new JButton();
	        btn_loop.addActionListener(new ActionListener() {
	            public void actionPerformed(final ActionEvent arg0) {
	                if (audioClip != null)
	                    audioClip.loop();    // 循環播放
	            }
	        });
	        btn_loop.setText("循    環");
	        btn_loop.setBounds(208, 60, 80, 28);
	        getContentPane().add(btn_loop);
	 }
	 

		    public static void main(String args[]) {
		        EventQueue.invokeLater(new Runnable() {
		            public void run() {
		                try {
		                    AudioPlayDemo frame = new AudioPlayDemo();
		                    frame.setVisible(true);
		                } catch (Exception e) {
		                    e.printStackTrace();
		                }
		            }
		        });
		    }
}

相關文章
相關標籤/搜索