源码:http://yuncode.net/code/c_5052c1fddaa6538
- 01 import javax.swing.*;
- 02 import javax.sound.midi.*;
- 03 import java.awt.GridLayout;
- 04 import java.io.File;
- 05
- 06 public class MidiPlayer extends JFrame {
- 07 @SuppressWarnings("deprecation")
- 08 MidiPlayer(String song) {
- 09 super(song);
- 10 setSize(300, 150);
- 11 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- 12 MidiPanel midi = new MidiPanel(song);
- 13 JPanel pane = new JPanel();
- 14 pane.add(midi);
- 15 setContentPane(pane);
- 16 show();
- 17 }
- 18
- 19 public static void main(String[] arguments) {
- 20
- 21 MidiPlayer pm = new MidiPlayer("c:\\1.midi"); // midi文件
- 22
- 23 }
- 24 }
- 25
- 26 class MidiPanel extends JPanel implements Runnable {
- 27 Thread runner;
- 28 JProgressBar progress = new JProgressBar();
- 29 Sequence currentSound;// 音序
- 30 Sequencer player;// 默认音序器
- 31 String songFile;// 歌曲
- 32
- 33 MidiPanel(String song) {
- 34 super();
- 35 songFile = song;
- 36 JLabel label = new JLabel("Playing file...");
- 37 setLayout(new GridLayout(2, 1));
- 38 add(label);
- 39 add(progress);
- 40 if (runner == null) {
- 41 runner = new Thread(this);
- 42 runner.start();
- 43 }
- 44 }
- 45
- 46 public void run() {
- 47
- 48 try {
- 49
- 50 System.out.println(songFile);
- 51 File file = new File(songFile);
- 52
- 53 currentSound = MidiSystem.getSequence(file);// 获取音序文件
- 54 player = MidiSystem.getSequencer();// 获取音序器
- 55 player.open();
- 56 player.setSequence(currentSound);// 设置音序器播放指定音乐文件
- 57
- 58 progress.setMinimum(0);
- 59 progress.setMaximum((int) player.getMicrosecondLength());// 设置最大位歌曲时间
- 60
- 61 player.start();
- 62 while (player.isRunning()) {
- 63 progress.setValue((int) player.getMicrosecondPosition());// 设置播放文件显示当前播放进度
- 64 try {
- 65 Thread.sleep(1000);
- 66 } catch (Exception e) {
- 67 // TODO: handle exception
- 68 }
- 69 }
- 70 player.close();
- 71 } catch (Exception e) {
- 72 // TODO: handle exception
- 73 }
- 74 }
- 75
- 76 }
转载于:https://blog.51cto.com/laoye/991170