วันพุธที่ 20 มีนาคม พ.ศ. 2556

LAB 8_PlayMidi

 PlayMidi(LAB8) 

import java.awt.event.*;
import javax.swing.*;
import javax.sound.midi.*;
import java.awt.GridLayout;
import java.io.File;
public class PlayMidi extends JFrame{
    public PlayMidi(String title){
        super(title);
        setSize(180,100);
        MidiPanel midi=new MidiPanel("./sounds/midi.midi");
        JPanel pane=new JPanel();
        pane.add(midi);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setContentPane(pane);
        setVisible(true);
    }
    public static void main(String[]args){
        PlayMidi myMidi=new PlayMidi("Java Sound MIDI");
    }
}
class MidiPanel extends JPanel implements Runnable{
    Thread runner;
    JProgressBar progress=new JProgressBar();
    Sequence currentSound;
    Sequencer player;
    String songFile;
    public 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{
            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(InterruptedException e){}
            }
            progress.setValue((int)player.getMicrosecondPosition());
            player.close();
        }catch(Exception e){
            System.err.println(e);
        }
    }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น