服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

教你如何使用javax.sound.midi包


  package lookbook.midi;
import javax.sound.midi.*;
import java.io.*;
import java.net.*;
/**
* <p>title: </p>
* <p>description: how to use java midi from javax.sound.midi´s package</p>
* <p>copyright: copyright (c) 2003</p>
* <p>company: </p>
* @author lookbook
* @version 1.0
*/

public class midimain {
private static string midifile = "town.mid";
private static string midiuri = "http://hostname/midifile";
private sequence sequence =null;
public midimain() {
this.loadandplay();
}
public void loadandplay(){
try {
// from file
sequence = midisystem.getsequence(new file(midifile));

// from url
// sequence = midisystem.getsequence(new url("http://hostname/midifile"));

// create a sequencer for the sequence
sequencer sequencer = midisystem.getsequencer();
sequencer.open();
sequencer.setsequence(sequence);

//determining the duration of a midi audio file
double durationinsecs = sequencer.getmicrosecondlength() / 1000000.0;
system.out.println("the duration of this audio is "+durationinsecs+"secs.");

//determining the position of a midi sequencer
double seconds = sequencer.getmicrosecondposition() / 1000000.0;
system.out.println("the position of this audio is "+seconds+"secs.");

//setting the volume of playing midi audio
if (sequencer instanceof synthesizer) {
synthesizer synthesizer = (synthesizer)sequencer;
midichannel[] channels = synthesizer.getchannels();

// gain is a value between 0 and 1 (loudest)
double gain = 0.9d;
for (int i=0; i<channels.length; i++) {
channels[i].controlchange(7, (int)(gain * 127.0));
}
}

// start playing
sequencer.start();

//determining the position of a midi sequencer
thread.currentthread().sleep(5000);
seconds = sequencer.getmicrosecondposition() / 1000000.0;
system.out.println("the position of this audio is "+seconds+"secs.");

//add a listener for meta message events
sequencer.addmetaeventlistener(
new metaeventlistener() {
public void meta(metamessage event) {
// sequencer is done playing
if (event.gettype() == 47) {
system.out.println("sequencer is done playing.");
}
}
});
}catch (malformedurlexception e) {
}catch (ioexception e) {
}catch (midiunavailableexception e) {
}catch (invalidmididataexception e) {
}catch (interruptedexception e){
}
}

public static void main(string[] args) {
midimain midi = new midimain();

}

}

扫描关注微信公众号