View Javadoc

1   package com.jamesbryangraves.bob.midi;
2   
3   import java.util.ArrayList;
4   import java.util.List;
5   
6   import javax.sound.midi.InvalidMidiDataException;
7   import javax.sound.midi.MidiEvent;
8   import javax.sound.midi.MidiMessage;
9   import javax.sound.midi.MidiUnavailableException;
10  import javax.sound.midi.Receiver;
11  import javax.sound.midi.ShortMessage;
12  
13  import junit.framework.JUnit4TestAdapter;
14  import junit.framework.TestCase;
15  
16  import org.junit.Before;
17  import org.junit.Test;
18  
19  import com.jamesbryangraves.bob.music.MusicContext;
20  
21  public class BobMidiSequencerTest extends TestCase {
22  	
23  	private BobMidiSequencer sequencer;
24  	private long[] results = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
25  	public long timestamp;
26  	
27  	@Before	public void setUp() throws MidiUnavailableException, InvalidMidiDataException {
28  		MusicContext musicContext = new MusicContext();
29  		musicContext.setMeterNumerator(4);
30  		musicContext.setMeterDenominator(4);
31  		musicContext.setResolution(16);
32  		musicContext.setBpm(60);
33  		
34  		BobMidiSequence sequence = new BobMidiSequence(musicContext);
35  		BobMidiTransmitter transmitter = new BobMidiTransmitter();
36  		transmitter.setReceiver(new TestReceiver());
37  		BobMidiTrack track = new BobMidiTrack();
38  		track.setTransmitter(transmitter);
39  		List<BobMidiTrack> tracks = new ArrayList<BobMidiTrack>();
40  		tracks.add(track);
41  		sequence.setTracks(tracks);
42  		
43  		
44  		sequencer = new BobMidiSequencer();
45  		sequencer.setSequence(sequence);
46  		timestamp = System.currentTimeMillis();
47  		
48  	}
49  	
50  	@Test public void testSequencer() throws MidiUnavailableException, InvalidMidiDataException {
51  			
52  		for(int i = 0; i < 10; i++) {
53  			ShortMessage message = new ShortMessage();
54  			message.setMessage(ShortMessage.NOTE_ON, 0, 60, i);//nVelocity);
55  			sequencer.getSequence().getTrack(0).add(new MidiEvent(message, 
56  					i * sequencer.getSequence().getMusicContext().getTicksPerBeat()));
57  		}
58  		
59  		sequencer.open();
60  		new Thread() {
61  			public void run() {
62  				sequencer.start();
63  			}
64  		}.start();
65  		
66  		while(results[9] == 0);
67  		
68  		for(int i = 1; i < 10; i++)
69  			assertTrue("Expecting 1 Event about every 1000 milliseconds (60 bpm) : " + results[i], 
70  					(990 < results[i] && results[i] < 1010));
71  		
72  		
73  	}
74  	
75  	private class TestReceiver implements Receiver {
76  		
77  		public void send(MidiMessage message, long ts) {
78  			int i = message.getMessage()[2] & 0xFF;
79  			results[i] = ts - timestamp;
80  			timestamp = ts;
81  		}
82  		
83  		public void close() {	
84  		}
85  	}
86  	
87  	public static junit.framework.Test suite() {
88  		return new JUnit4TestAdapter(BobMidiSequencerTest.class);
89  	}
90  
91  }