import javax.swing.*; |
import javax.sound.midi.*; |
import java.awt.GridLayout; |
import java.io.File; |
public class MidiPlayer extends JFrame { |
@SuppressWarnings ( "deprecation" ) |
MidiPlayer(String song) { |
super (song); |
setSize( 300 , 150 ); |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
MidiPanel midi = new MidiPanel(song); |
JPanel pane = new JPanel(); |
pane.add(midi); |
setContentPane(pane); |
show(); |
} |
public static void main(String[] arguments) { |
MidiPlayer pm = new MidiPlayer( "c:\\1.midi" ); // midi文件 |
} |
} |
class MidiPanel extends JPanel implements Runnable { |
Thread runner; |
JProgressBar progress = new JProgressBar(); |
Sequence currentSound; // 音序 |
Sequencer player; // 默认音序器 |
String songFile; // 歌曲 |
MidiPanel(String song) { |
super (); |
songFile = song; |
JLabel label = new JLabel( "Playing file..." ); |
setLayout( new GridLayout( 2 , 1 )); |
add(label); |
add(progress); |
if (runner == null ) { |
runner = new Thread( this ); |
runner.start(); |
} |
} |
public void run() { |
try { |
System.out.println(songFile); |
File file = new File(songFile); |
currentSound = MidiSystem.getSequence(file); // 获取音序文件 |
player = MidiSystem.getSequencer(); // 获取音序器 |
player.open(); |
player.setSequence(currentSound); // 设置音序器播放指定音乐文件 |
progress.setMinimum( 0 ); |
progress.setMaximum(( int ) player.getMicrosecondLength()); // 设置最大位歌曲时间 |
player.start(); |
while (player.isRunning()) { |
progress.setValue(( int ) player.getMicrosecondPosition()); // 设置播放文件显示当前播放进度 |
try { |
Thread.sleep( 1000 ); |
} catch (Exception e) { |
// TODO: handle exception |
} |
} |
player.close(); |
} catch (Exception e) { |
// TODO: handle exception |
} |
} |
} |
初级程序员
by: 云代码会员 发表于:2017-06-05 22:11:37 顶(0) | 踩(0) 回复
就这么点吗
回复评论