import javax.sound.midi.*; /** * @author [av1m](https://www.github.com/av1m) * @author [Ilan Nizard](https://fr.linkedin.com/in/ilan-nizard-74a222140) *
* Thanks to [@wadael](https://github.com/wadael) for the initiation *
*/ public class Fibo { /** * Calculate the fibonacci sequence * * @param n * @return long */ private static long fibonacci(final long n) { return (1L >= n) ? n : Fibo.fibonacci(n - 1L) + Fibo.fibonacci(n - 2L); } /** * Function that calls playMidiSong according to a note * * @param note */ public static int getTone(int note) { switch (note) { case 0: case 7: return 63; // Mi bemol case 1: case 8: return 64; // Mi case 3: return 68; // Sol # case 4: return 57; // La case 5: return 59; // Si case 6: return 73; // Do # case 9: return 0; default: return 66; // Fa # } } /** * main * * @param args nothing expected */ public static void main(String[] args) throws MidiUnavailableException, InterruptedException { final int NUMBER_ITERATION = 40; final Synthesizer midiSynth = MidiSystem.getSynthesizer(); long fiboNumber = 0; midiSynth.open(); // Get and load default instrument and schannel lists final Instrument[] instr = midiSynth.getDefaultSoundbank().getInstruments(); final MidiChannel[] mChannels = midiSynth.getChannels(); midiSynth.loadInstrument(instr[0]); // Load an instrument for (long i = 1; i <= NUMBER_ITERATION; i++) { fiboNumber = Fibo.fibonacci(i); System.out.println("== Fibo number : " + fiboNumber); String notes = String.valueOf(fiboNumber); for (int j = 0; j < notes.length(); j++) { // Get size of string (long fibo) && transform each char to int int oneSong = Character.getNumericValue(notes.charAt(j)); System.out.println("song Played : " + oneSong); mChannels[0].noteOn(Fibo.getTone(oneSong), 100); Thread.sleep(250L); // wait time in milliseconds to control duration mChannels[0].noteOff((int) i); // Turn off the note } } midiSynth.close(); } }