问题,制作midi文件后,将其倒入西贝柳斯软件中看乐谱发现总多出一个小节,小节用全因休止符占位;
原因:写midi的时候切记音符时间戳一定要从0开始计算那,被特么坑死了;
/**
* 测试写出midi文件
* 音符样例 音符的音高 0-127(48是C大调的do。48,50,52,53,55,57,59就是do re,mi,fa,so,la,xi)
* 音符样例 音符的音高 0-127(60是中间C的do。60,62,64,65,67,69,71就是do re,mi,fa,so,la,xi)
*/
public static void writeTest00() {
try {
int channel = 6;
int resolution = 64;
System.out.println("resolution:"+resolution);
int resolution2 = 32;
System.out.println("resolution2:"+resolution2);
int start = 0;//就这块在计算时间戳开始一定要从0开始
int stop = 63;
int sound = 100;
int inFu = 60;
Sequence seq = new Sequence(Sequence.PPQ, resolution);
Track track = seq.createTrack();
for(int i = 1;i<=5;i++){
ShortMessage a = new ShortMessage();
ShortMessage b = new ShortMessage();
switch (i){
case 1:
inFu = 60;
break;
case 2:
inFu = 62;
start = stop+1;
stop = start+resolution-1;
break;
case 3:
inFu = 64;
start = stop+1;
stop = start+resolution2-1;
break;
case 4:
inFu = 65;
start = stop+1;
stop = start+resolution2-1;
break;
case 5:
start = stop+1;
stop = start+resolution-1;
inFu = 67;
break;
}
//开
System.out.println("start:"+start);
a.setMessage(144,channel,inFu,sound);
MidiEvent noteOn=new MidiEvent(a,start);
track.add(noteOn);
//停
System.out.println("stop:"+stop);
b.setMessage(128,channel,inFu,sound);
MidiEvent noteOff=new MidiEvent(b,stop);
track.add(noteOff);
}
// writeFile(seq);
Sequencer player = MidiSystem.getSequencer();
player.setTempoInBPM(48);
player.open();
player.setSequence(seq);
player.start();
while (player.isRunning()) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
player.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static final String RESOURCE_PREFIX = "/profile";
/**
* 写文件
* @param seq
*/
public static String writeFile(Sequence seq){
String filePath = "";
try {
String baseDir = "/usr/local/project/uploadPath";
if (StringUtils.isEmpty(baseDir)){
logger.info("未获取到baseDir");
return null;
}
String truePath = baseDir+"/upload";
String datePath = DateUtils.datePath() + "/";
String mName = IdUtils.fastUUID() + ".mid";
String midiName = datePath + mName;
String folderPath = truePath + "/" + datePath;
logger.info("folderPath:"+folderPath);
File folderFile = new File(folderPath);
if (!folderFile.exists()){
folderFile.mkdirs();
}
String writePath = truePath+"/"+midiName;
logger.info("写入地址:"+writePath);
File file = new File(writePath);
MidiFileWriter writer = new StandardMidiFileWriter();
writer.write(seq, 0, file);
int dirLastIndex = baseDir.length() + 1;
String currentDir = StringUtils.substring(truePath, dirLastIndex);
String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + midiName;
logger.info("pathFileName:http://localhost:8080/platform"+pathFileName);
filePath = pathFileName;
}catch (Exception e){
e.printStackTrace();
}
return filePath;
}