예제 #1
0
        public Composition Generate()
        {
            int trackNo = composition.Tracks.Count;
            Composition newComp = new Composition();

            Parallel.For(0, trackNo, i =>
                {
                    PatchNames instrument = composition.Tracks[i].Instrument;
                    Console.WriteLine("Generating track {0} with instrument {1}", i, instrument.ToString());
                    var melodySeq = composition.Tracks[i].GetMainSequence() as MelodySequence;

                    MarkovChainGenerator chain = new MarkovChainGenerator(instrument,2, melodySeq.Length);
                    chain.AddMelody(melodySeq);
                    var notes = chain.Generate();

                    Track track = new Track(instrument, (byte)(i + 1));
                    track.AddSequence(notes);
                    newComp.Add(track);
                    //var notes = trackGenerator.Generate();
                    Console.WriteLine("Done Generating track {0}", i);

                });

            return newComp;
        }
예제 #2
0
        static void ANNFFNAccomp()
        {
            Databank db = new Databank("lib");
            var cat = db.Load("Classical");

            Composition inputComp = cat.Compositions[6];
            MelodySequence inputSeq = inputComp.Tracks[0].GetMainSequence() as MelodySequence;

            AccompanimentGeneratorANNFF gen = new AccompanimentGeneratorANNFF(cat, PatchNames.Acoustic_Grand);
            //gen.Initialize();
            gen.SetSequence(inputSeq);
            gen.Train();

            var outMel = gen.Generate();

            MusicPlayer player = new MusicPlayer();

            Composition comp = new Composition();
            Track t = new Track(PatchNames.Orchestral_Strings, 6);
            t.AddSequence(outMel);
            comp.Add(t);
            comp.Add(inputComp.Tracks[0]);
            player.Play(comp);
            comp.WriteToMidi("ann_ff_accomp.mid");
        }
예제 #3
0
        /// <summary>
        /// Adds a track and returns the reference
        /// </summary>
        /// <param name="seq"></param>
        /// <param name="gen"></param>
        /// <returns>Reference of added track</returns>
        public Track Add(MelodySequence seq, INoteGenerator gen)
        {
            if (gen as DrumGenerator != null || gen.Instrument == PatchNames.Helicopter)
                return AddPercussionTrack(seq, gen);

            Track t = new Track(gen.Instrument, (byte)channelIndex++);
            t.AddSequence(seq);
            ActiveComposition.Tracks.Add(t);
            generators.Add(gen);

            if (OnCompositionChange != null)
                OnCompositionChange(this, new EventArgs());

            return t;
        }
예제 #4
0
 static void WriteMelodyToFile(MelodySequence seq, string filename)
 {
     Composition comp = new Composition();
     Track track = new Track(PatchNames.Acoustic_Grand, 1);
     track.AddSequence(seq);
     comp.Add(track);
     comp.WriteToMidi(filename);
 }
예제 #5
0
 static void Test9()
 {
     MusicPlayer player = new MusicPlayer();
     Console.WriteLine("Harmony Test");
     //ChromaticToneDuration, ChromaticTone, MelodicBigram, RhythmicBigram
     MetricSimilarity cosine = new MetricSimilarity(GetMelodySequence(@"test\other\ff7tifa.mid"), new ChromaticToneDuration());
     GeneticGenerator evolver = new GeneticGenerator(cosine);
     var notes = evolver.Generate();
     SimpleChord ch = new SimpleChord();
     var melody = notes;
     HarmonySequence harmony = ch.GetHarmonySequence(melody);
     Track t1 = new Track(PatchNames.Acoustic_Grand, 2);
     t1.AddSequence(melody);
     Track t2 = new Track(PatchNames.Church_Organ, 1);
     t2.AddSequence(harmony);
     Composition comp = new Composition();
     // comp.Add(t1);
     comp.Add(t2);
     player.Play(comp);
     Console.ReadLine();
     return;
 }
예제 #6
0
        static void Test8()
        {
            MusicPlayer player = new MusicPlayer();

            Console.WriteLine("Hidden Markov Model");
            var m1 = GetMelodySequence(@"test\other\frere.mid");
            var m2 = GetMelodySequence(@"test\other\babaa.mid");
            var m3 = GetMelodySequence(@"test\other\twinkle.mid");

            var m4 = GetMelodySequence(@"test\hagrid.mid");
            var m5 = GetMelodySequence(@"test\harry.mid");
            var m6 = GetMelodySequence(@"test\harry2.mid");
            MarkovGenerator markov = new MarkovGenerator(new MelodySequence[] { m6 });
            while (true)
            {
                Composition comp = new Composition();

                GeneticGenerator gen = new GeneticGenerator(new MetricSimilarity(m6, new IMetric[] { new Rhythm(), new RhythmicBigram(), new RhythmicInterval() }));
                var notes2 = gen.Generate();
                Track t2 = new Track((PatchNames)0, 10);
                MelodySequence s = new MelodySequence();
                s.AddPause((int)Durations.wn * 10);
                foreach (Note n in notes2.Notes)
                {
                    if (n.Pitch <= 0)
                        n.Pitch = 0;
                    else if (n.Pitch > 48)
                        n.Pitch = 40;
                    else if (n.Pitch > 70)
                        n.Pitch = 35;
                    else
                    {
                        n.Pitch = 49;
                        n.Duration *= 4;
                        n.Velocity = 50;
                        s.AddPause(n.Duration * 2);
                    }
                    s.AddNote(n);
                }
                t2.AddSequence(s);

                var notes3 = markov.Generate().Notes as Note[];

                MelodySequence baseseq = new MelodySequence();

                int max_dur = 0;
                int max_index = 0;
                for (int i = (int)(notes3.Length * 0.7f); i < notes3.Length; i++)
                {
                    if (notes3[i].Duration > max_dur)
                    {
                        max_dur = notes3[i].Duration;
                        max_index = i;
                    }
                }
                Note last_note = null;
                for (int i = 0; i < max_index; i++)
                {
                    last_note = notes3[i];
                    baseseq.AddNote(last_note);
                }
                baseseq.AddNote(new Note(last_note.Pitch - 12, last_note.Duration));
                baseseq.AddNote(new Note(last_note.Pitch - 24, last_note.Duration * 2));
                baseseq.AddPause(last_note.Duration * 32);

                Track t = new Track(PatchNames.Vibraphone, 1);

                var b1 = baseseq.Clone() as MelodySequence;
                var b2 = baseseq.Clone() as MelodySequence;
                var b3 = baseseq.Clone() as MelodySequence;
                b1.Transpose(12);
                b2.Transpose(6);
                b3.Transpose(-12);
                t.AddSequence(baseseq);
                t.AddSequence(b1);
                t.AddSequence(b2);
                t.AddSequence(b3);

                comp.Add(t);
                comp.Add(t2);
                Console.WriteLine("Press enter key to listen");
                Console.ReadLine();
                player.Play(comp);
            }
        }
예제 #7
0
        static void MarkovAccompTest()
        {
            Databank db = new Databank("lib");
            var cat = db.Load("Classical");

            Composition inputComp = cat.Compositions[6];
            MelodySequence inputSeq = inputComp.Tracks[0].GetMainSequence() as MelodySequence;

            AccompanyGeneratorMarkov gen = new AccompanyGeneratorMarkov(cat, PatchNames.Orchestral_Strings);

            var outMel = gen.Generate(inputSeq, 10);

            MusicPlayer player = new MusicPlayer();

            Composition comp = new Composition();
            Track t = new Track(gen.Instrument, 6);
            t.AddSequence(outMel);
            comp.Add(t);
            comp.Add(inputComp.Tracks[0]);
            player.Play(comp);
            comp.WriteToMidi("markov_model_accomp.mid");
        }
예제 #8
0
        static void Main(string[] args)
        {
            /*Feed forward neural network
            Group notes into 3
            Classify all groups in existing songs as 1, all other combinations as 0.

            Use as fitness function

            Use HMM decode as fitness function GA*/

               /* Databank db = new Databank("lib");

            List<MelodySequence> drumSeqs = new List<MelodySequence>();
            var comps = new Composition[][] { db.Load("Classic Rock").Compositions, db.Load("Jazz").Compositions, Utils.LoadCompositionsParallel(@"D:\Sync\4th year\Midi\Library2\Drums") };

            foreach(Composition[] catt in comps)
            {
                foreach(var c in catt)
                {
                    foreach(var t in c.Tracks)
                    {
                        if(t.Channel == 10)
                        {
                            drumSeqs.Add(t.GetMainSequence() as MelodySequence);
                        }
                    }
                }
            }

            List<Composition> drums = new List<Composition>();
            foreach(var m in drumSeqs)
            {
                Composition c = new Composition();
                Track t = new Track(PatchNames.Acoustic_Grand, 10);
                t.AddSequence(m);
                c.Add(t);
                drums.Add(c);
            }

            var catdrum = new CompositionCategory("Drums", "lib/Drums", drums.ToArray());
            catdrum.Save("lib/Drums");
            Console.ReadLine();
            */

            /*Composition comp = Composition.LoadFromMIDI(@"C:\Users\1gn1t0r\Documents\git\GeneticMIDI\GeneticMIDI\bin\Debug\test\other\twinkle.mid");
            float time = Note.ToRealDuration(comp.GetLongestTrack().Duration);
            Console.WriteLine("Total time: {0}", time);
            MusicPlayer player = new MusicPlayer();
            player.Play(comp);
            Console.ReadLine();*/

            var twink = Composition.LoadFromMIDI(@"C:\Users\1gn1t0r\Documents\git\GeneticMIDI\GeneticMIDI\bin\Debug\test\other\twinkle.mid");

               Databank db = new Databank("lib");
            var cat = db.Load("Jazz");

            Codebook<Note> book = new Codebook<Note>();

            List<int[]> sequences = new List<int[]>();

            foreach(var comp in cat.Compositions)
            {
                foreach(var track in comp.Tracks)
                {
                    if(track.Instrument == PatchNames.Trumpet)
                    {
                        var mel = track.GetMelodySequence();
                        mel.Trim(80);
                        mel.StandardizeDuration();

                        book.Add(mel.Notes);
                        sequences.Add(book.ToCodes(mel.Notes));
                    }
                }
                if (sequences.Count > 10)
                    break;
            }

            DotNetLearn.Markov.HiddenMarkovModel hmm = new DotNetLearn.Markov.HiddenMarkovModel(60, book.TotalUniqueSymbols);
            hmm.UniformRandomPriors();
            hmm.MaxIterations = 50;
            hmm.Train(sequences.ToArray());

            var o = hmm.PredictObservationSequence(80);
            var newmel = new MelodySequence(book.Translate(o));

            Track t = new Track(PatchNames.Trumpet, 2);
            t.AddSequence(newmel);

            Console.ReadLine();
            MusicPlayer player = new MusicPlayer();
            player.Play(t);

            player.Stop();

            Console.ReadLine();

            /*
            var gen = new SamplingWithReplacement(cat, PatchNames.Acoustic_Grand);

            var mel = gen.Generate();

            Console.WriteLine(mel.ToString());
            MusicPlayer player = new MusicPlayer();
            player.Play(mel);

            Console.WriteLine("Press enter to save");
            Console.ReadLine();
            WriteMelodyToFile(gen.OriginalSequence, "sampling_in.mid");
            WriteMelodyToFile(mel, "sampling_out.mid");
            */

                /*  MusicPlayer player = new MusicPlayer();

                  //db.LoadAll();

                  AccompanyGeneratorMarkov genMark = new AccompanyGeneratorMarkov(cat);
                  var targetSeq = cat.Compositions[2].GetLongestTrack().GetMainSequence() as MelodySequence;
                  var seqTest = genMark.Generate(targetSeq,5);

                  Track trackTest = new Track(PatchNames.Orchestral_Strings, 2); trackTest.AddSequence(seqTest);

                  Track targetTrack = new Track(PatchNames.Acoustic_Grand, 3); targetTrack.AddSequence(targetSeq);

                  Composition comp = new Composition();
                  comp.Add(trackTest);
                  comp.Add(targetTrack);

                  player.Play(comp);

                  return;*/

                /*   Databank db = new Databank("lib");
                   var cat = db.Load("Classical");
                   //AccompanimentGenerator2 Test
                   AccompanimentGenerator2 gen = new AccompanimentGenerator2(cat, PatchNames.Orchestral_Strings);
                   gen.Train();
                   //
                   Composition comp = Composition.LoadFromMIDI(@"D:\Sync\4th year\Midi\Library2\Classical\Mixed\dvorak.mid");
                   //var comp = Composition.LoadFromMIDI(@"C:\Users\1gn1t0r\Documents\git\GeneticMIDI\GeneticMIDI\bin\Debug\test\ff7tifa.mid");
                   gen.SetSequence(comp.Tracks[0].GetMainSequence() as MelodySequence);

                   MusicPlayer player = new MusicPlayer();

                       Console.WriteLine("Press enter to listen");
                       Console.ReadLine();

                       var mel = gen.Generate();
                       Composition newComp = new Composition();
                       Track newTrack = new Track(PatchNames.Orchestral_Strings , 2);
                       newTrack.AddSequence(mel);
                       newComp.Add(newTrack);
                       /*comp.Tracks[0].Instrument = PatchNames.Acoustic_Grand; (comp.Tracks[0].GetMainSequence() as MelodySequence).ScaleVelocity(0.8f);
                       /* newComp.Tracks.Add(comp.Tracks[0]);

                       player.Play(newComp);*/

                Console.ReadLine();
        }
예제 #9
0
        static void InstrumentalTest()
        {
            Databank db = new Databank("lib");
            var cat = db.Load("Classical");

            InstrumentalGenerator gen = new InstrumentalGenerator(cat);
            gen.Initialize();
            var outMel = gen.GenerateInstrument(PatchNames.Acoustic_Grand, 40);

            MusicPlayer player = new MusicPlayer();
            player.Play(outMel);

            Composition comp = new Composition();
            Track t = new Track(PatchNames.Acoustic_Grand, 3);
            t.AddSequence(outMel);
            comp.Add(t);
            comp.WriteToMidi("instrumental_acousticgrand.mid");
        }
예제 #10
0
        static void GeneticTest()
        {
            Databank db = new Databank("lib");
            var cat = db.Load("Classical");

            MetricSimilarity cosine = MetricSimilarity.GenerateMetricSimilarityMulti(cat.Compositions, new IMetric[] { new ChromaticToneDistance(), new MelodicInterval(), new ChromaticToneDuration(), new RhythmicBigram() });
            GeneticGenerator gen = new GeneticGenerator(cosine, PatchNames.Orchestral_Strings, cat);
            gen.OnPercentage += (sender, percentage, fitness) => { Console.WriteLine("{0}: {1}", percentage, fitness); };
            gen.MaxGenerations = 1000;
            var outMel = gen.Generate();

            MusicPlayer player = new MusicPlayer();
            player.Play(outMel);

            Composition comp = new Composition();
            Track t = new Track(gen.Instrument, 3);
            t.AddSequence(outMel);
            comp.Add(t);
            comp.WriteToMidi("genetic_cosine_all.mid");
        }
예제 #11
0
 static void DemoTest2()
 {
     MusicPlayer player = new MusicPlayer();
     Composition comp = new Composition();
     Track track1 = new Track(PatchNames.Acoustic_Grand, 1);
     Track track2 = new Track(PatchNames.Cello, 2);
     Console.WriteLine("Hidden Markov Model, constant duration, twinkle");
     var mel1 = GetMelodySequence(@"test\harry.mid");
     var stoch = new StochasticGenerator(new MelodySequence[] { mel1 });
     track1.AddSequence(stoch.Generate());
     track2.AddSequence(stoch.Generate());
     //comp.Add(track1);
     comp.Add(track2);
     player.Play(comp);
     return;
 }
예제 #12
0
        /// <summary>
        /// Loads a Harmony Sequence though
        /// </summary>
        /// <param name="f"></param>
        /// <returns></returns>
        public static Composition LoadMidiType1(MidiFile f)
        {
            Composition comp = new Composition();
            int c = 1;
            foreach(var trackEvents in f.Events)
            {
                Track t = new Track();

                t.Channel = (byte)c++;
                TempoEvent tempo = new TempoEvent((int)(Note.ToRealDuration((int)Durations.qn, 60) * 1000000), 0);
                HarmonySequence seq = new HarmonySequence();
                long lastAbsTime = -1;

                List<int> chordNotes = new List<int>(); int chordDuration = 0;
                PatchNames instr = (PatchNames)9999;

                bool add = true;
                foreach(var e in trackEvents)
                {
                    if (e as TempoEvent != null)
                    {
                        tempo = (TempoEvent)e;
                    }
                    if (e as PatchChangeEvent != null)
                    {
                        var p = e as PatchChangeEvent;
                        t.Instrument = (PatchNames)p.Patch;

                        if(t.Instrument == instr)
                        {
                            break;
                        }
                        instr = t.Instrument;
                        /*if(t.Duration < 1)
                        {
                            foreach(var t_ in comp.Tracks)
                                if(t_.Instrument == (PatchNames)p.Patch)
                                {
                                    t = t_;
                                    seq = t_.GetMainSequence() as HarmonySequence;
                                    add = false;
                                    break;
                                }
                        }*/
                    }
                    NoteOnEvent on = e as NoteOnEvent;

                    if (on != null && on.OffEvent != null)
                    {
                        int newDuration = Note.ToNoteLength(on.NoteLength, f.DeltaTicksPerQuarterNote, tempo.Tempo);

                        if (on.AbsoluteTime == lastAbsTime && chordDuration==newDuration)//skip chords
                        {
                            chordNotes.Add(on.NoteNumber);
                        }
                        else
                        {
                            Chord lastChord = new Chord(chordNotes.ToArray(), chordDuration);
                            chordNotes.Clear(); chordDuration = 0;
                            seq.AddChord(lastChord);

                            chordNotes.Add(on.NoteNumber);
                        }

                        chordDuration = newDuration;
                        lastAbsTime = on.AbsoluteTime;
                    }
                }
                if(chordNotes.Count > 0)
                {
                    Chord lastChord = new Chord(chordNotes.ToArray(), chordDuration);
                    chordNotes.Clear(); chordDuration = 0;
                    seq.AddChord(lastChord);
                }

                t.AddSequence(seq);
                if (!comp.Tracks.Contains(t) && t.Duration > 0 && add)
                    comp.Add(t);
            }

            return comp;
        }
예제 #13
0
        public void Next()
        {
            ActiveComposition = new Composition();
            int i = 1;
            foreach(var gen in generators)
            {
                byte channel = (byte)i++;
                if(gen as DrumGenerator != null)
                    channel = 10;
                Track t = new Track(gen.Instrument, channel);
                MelodySequence seq = gen.Next();
                t.AddSequence(seq);
                ActiveComposition.Add(t);
            }

            if (OnCompositionChange != null)
                OnCompositionChange(this, new EventArgs());
        }
예제 #14
0
        private Track AddPercussionTrack(MelodySequence seq, INoteGenerator gen)
        {
            Track t = new Track(gen.Instrument, 10);

            for(int i  = 0 ; i < ActiveComposition.Tracks.Count; i++)
            {
                var ctrack = ActiveComposition.Tracks[i];
                if(ctrack.Channel == 10)
                {
                    ctrack.Clear();
                    ActiveComposition.Tracks.RemoveAt(i);
                    break;
                }
            }

            t.AddSequence(seq);
            ActiveComposition.Tracks.Add(t);
            generators.Add(gen);
            if (OnCompositionChange != null)
                OnCompositionChange(this, new EventArgs());
            return t;
        }
예제 #15
0
 public Composition Generate(IEnumerable<PatchNames> instrs, int seed = 0)
 {
     lastInstruments = instrs;
     int i = 1;
     Composition comp = new Composition();
     foreach (PatchNames instrument in instrs)
     {
         if (instruments.ContainsKey(instrument))
         {
             Track t = new Track(instrument, (byte)(i++));
             t.AddSequence(GenerateInstrument(instrument, seed));
             comp.Add(t);
         }
     }
     return comp;
 }