001package net.kreatious.pianoleopard.midi.event; 002 003import java.util.Optional; 004 005import javax.sound.midi.MidiEvent; 006import javax.sound.midi.MidiMessage; 007import javax.sound.midi.ShortMessage; 008 009/** 010 * Creates {@link Event} subclasses from {@link MidiEvent}s 011 * 012 * @author Jay-R Studer 013 */ 014public class EventFactory { 015 /** 016 * Private constructor to prevent instantiation by external consumers 017 */ 018 private EventFactory() { 019 } 020 021 /** 022 * Constructs a new immutable subclass of {@link Event} with the appropriate 023 * information. 024 * 025 * @param event 026 * the {@link MidiEvent} to create an event for 027 * @param cache 028 * the {@link TempoCache} to convert timestamps with 029 * @return An optional containing a supported event type, otherwise an empty 030 * optional. 031 */ 032 public static Optional<Event> create(MidiEvent event, TempoCache cache) { 033 if (event.getMessage() instanceof ShortMessage == false) { 034 return Optional.empty(); 035 } 036 037 final ShortMessage message = (ShortMessage) event.getMessage(); 038 final long time = cache.ticksToMicroseconds(event.getTick()); 039 return create(message, time); 040 } 041 042 /** 043 * Constructs a new immutable subclass of {@link Event} with the appropriate 044 * information. 045 * 046 * @param message 047 * the {@link MidiMessage} to create an event for 048 * @param time 049 * the time in microseconds to create an event for 050 * @return An optional containing a supported event type, otherwise an empty 051 * optional. 052 */ 053 public static Optional<Event> create(MidiMessage message, long time) { 054 if (message instanceof ShortMessage == false) { 055 return Optional.empty(); 056 } 057 return create((ShortMessage) message, time); 058 } 059 060 private static Optional<Event> create(ShortMessage message, long time) { 061 if (NoteEvent.canCreate(message)) { 062 return Optional.of(new NoteEvent(message, time)); 063 } else if (PedalEvent.canCreate(message)) { 064 return Optional.of(new PedalEvent(message, time)); 065 } else { 066 return Optional.empty(); 067 } 068 } 069}