For the past few days, I've been trying to code a metronome in Java for practice. I have made a simple 4/4 midi beat that the program plays with the use of javax.sound.midi library.
My main issue is that the sequencer appears to play the first beat off-time. If I set the sequence to loop, this occurs only the on the first loop. On a side note if I change the track's bpm, it resets after the first loop.
Also, I have tried multiple midi files just in case there was an issue with the midi file that I created but all my tests had the same results.
Here is my code that handles the midi playback:
public class MidiHandler
{
private Sequencer sequencer;
private Sequence seq;
private float newTempoFactor;
public MidiHandler()
{
try
{
sequencer = MidiSystem.getSequencer();
if (sequencer == null)
{
System.err.println("Sequencer not supported");
}
sequencer.open();
}
catch (MidiUnavailableException ex)
{
Logger.getLogger(MidiHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void setAudioTrack(String filePath)
{
try
{
seq= MidiSystem.getSequence(new File(filePath));
sequencer.setSequence(seq);
}
catch (InvalidMidiDataException | IOException ex)
{
Logger.getLogger(MidiHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void playTrack(float bpm) throws InterruptedException
{
try
{
seq=editEvents();//editEvents() method pushes all midi events 100 ticks forward
sequencer.setSequence(seq);
}
catch (InvalidMidiDataException ex)
{
Logger.getLogger(MidiHandler.class.getName()).log(Level.SEVERE, null, ex);
}
sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
sequencer.start();
//sequencer.setTempoInBPM(bpm);
newTempoFactor=bpm/120;
sequencer.setTempoFactor(newTempoFactor);//Default tempo is 120bpm --> Tempo factor =1
sequencer.setLoopStartPoint(100);//Shift the loop start/end by 100 ticks
sequencer.setLoopEndPoint(seq.getTickLength());
}
public Sequence editEvents()
{
Sequence seq= this.seq;
try
{
seq = MidiSystem.getSequence(new File("res//myTrack.mid"));
for (Track track : seq.getTracks())
{
for (int i=0; i < track.size(); i++)
{
MidiEvent event = track.get(i);
event.setTick(event.getTick()+100);
}
}
}
catch (InvalidMidiDataException | IOException ex)
{
Logger.getLogger(MidiHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return seq;
}
}
My main class
public class main
{
public static void main(String[] args)
{
try
{
MidiHandler mh = new MidiHandler();
mh.setAudioTrack("res//myTrack.mid");
mh.playTrack(120f);
}
catch (SecurityException | InterruptedException ex)
{
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}