Пример #1
0
 public void Play(Composition comp)
 {
     if (playingThread != null)
         playingThread.Abort();
     playingThread = new System.Threading.Thread(() => player.Play(comp));
     playingThread.Start();
 }
Пример #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
        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;
        }
Пример #4
0
        public void Clear()
        {
            this.channelIndex = 1;
            this.generators.Clear();
            this.ActiveComposition = new Composition();

            if (OnCompositionChange != null)
                OnCompositionChange(this, new EventArgs());
        }
Пример #5
0
        public TrackSelector(Composition comp)
        {
            this.composition = comp;
            InitializeComponent();

            foreach(var track in comp.Tracks)
            {
                AddTrackPlot(track);
            }
        }
Пример #6
0
        public static NCD FromCompositions(CompositionCategory category)
        {
            NCD ncd = new NCD();

            string savepath = GetSavePath(category);
            if (File.Exists(savepath))
            {
                ncd.Deserialize(savepath);
                return ncd;
            }

            Composition[] seqs = category.Compositions;

            ncd.songs = new string[seqs.Count()];

            int i = 0;
            int j = 0;
            foreach (var comp in seqs)
            {
                Console.WriteLine("NCD: {0}", j++ / seqs.Length);
                var c = comp;
                if (MaxTracks > 0)
                {
                    var newComp = new Composition();
                    for(int k = 0; k < MaxTracks && k < comp.Tracks.Count; k++)
                    {
                        newComp.Add(comp.Tracks[k]);
                    }
                    c = newComp;
                }

                ncd.songs[i++] = c.ToString();
            }

            string root = System.IO.Path.GetDirectoryName(savepath);
            if (!System.IO.Directory.Exists(root))
                System.IO.Directory.CreateDirectory(root);
            ncd.Serialize(savepath);

            return ncd;
        }
Пример #7
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");
        }
Пример #8
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;
 }
        public SampleSet LoadSampleSetFromComposition(Composition comp)
        {
            SampleSet set = new SampleSet();

            if (comp.Tracks.Count < 2)
                return set;

            var mainSeq = comp.Tracks[0].GetMainSequence() as MelodySequence;
            var mainNotes = mainSeq.ToArray();

            for (int track = 1; track < comp.Tracks.Count; track++)
            {
                Dictionary<Note, int> frequencies = new Dictionary<Note, int>();

                if (comp.Tracks[track].Instrument != instrument)
                {
                    // Console.WriteLine("\tSkipping instrument {0}", comp.Tracks[track].Instrument);
                    continue;
                }

                var seq = comp.Tracks[track].GetMainSequence() as MelodySequence;
                var notes = seq.ToArray();

                var max = Math.Min(mainNotes.Length, notes.Length);

                if (seq.TotalNoteDuration() < seq.TotalRestDuration())
                {
                    continue;
                }

                Console.WriteLine("\tAdding instrument {0}", comp.Tracks[track].Instrument);

                for (int j = 0; j < max; j++)
                {
                    if (notes[j].Velocity > 0)
                        notes[j].Velocity = 127;

                    notes[j].StandardizeDuration();

                    if (!frequencies.ContainsKey(notes[j]))
                        frequencies[notes[j]] = 1;
                    else frequencies[notes[j]] += 1;
                }

                // Filtering
                for (int j = 0; j < max; j++)
                {
                    double normalizedFrequency = frequencies[notes[j]] / (double)max;
                    //      if (normalizedFrequency < filterThreshold)
                    //          continue;

                    if (!noteHashes.ContainsKey(notes[j]))
                        noteHashes[notes[j]] = hash++;
                }

                int mainTime = 0;
                int accompTime = 0;
                int mainIndex = 0; int mainOff = 0;
                int accompIndex = 0; int accompOff = 0;
                const int GroupSize = 20;
                Note[] prevAccompanyNotesGroup = null;
                for (int j = GroupSize*2; mainIndex < max && accompIndex < max; j += GroupSize)
                {
                    mainIndex = j + mainOff;
                    accompIndex = j + accompOff;

                    if (mainIndex > max - 1 || accompIndex > max - 1)
                        break;

                    /*if (noteHashes[notes[j]] > MAX_OUTPUTS - 1)
                        continue;*/

                    Note[] accompanyNotesGroup = new Note[GroupSize];
                    Note[] mainNotesGroup = new Note[GroupSize];
                    for (int k = 0; k < GroupSize; k++)
                    {
                        accompanyNotesGroup[GroupSize - k - 1] = notes[accompIndex - k];
                        mainNotesGroup[GroupSize - k - 1] = mainNotes[mainIndex - k];
                    }
                    for (int k = 0; k < GroupSize; k++)
                    {
                        if (!noteHashes.ContainsKey(mainNotesGroup[k]) || !noteHashes.ContainsKey(accompanyNotesGroup[k]))
                            continue;
                        Note[] mainPrev = new Note[INPUT_NOTES];
                        for(int l = 0; l < INPUT_NOTES; l++)
                        {
                            mainPrev[l] = notes[accompIndex - k - l];
                        }
                        Note accomp = notes[accompIndex - k];
                        Sample s = GetSample(mainPrev, accomp);
                        set.Add(s);

                    }

                    mainTime += mainNotes[mainIndex].Duration;
                    accompTime += notes[accompIndex].Duration;

                    // Equalize every GroupSize notes
                    while (accompTime < mainTime)
                    {
                        accompIndex = j + (++accompOff);
                        if (accompIndex >= notes.Length - 1)
                            break;
                        accompTime += notes[accompIndex].Duration;
                    }
                }

            }

            return set;
        }
 public SampleSet GenerateSamples(Composition[] compositions)
 {
     SampleSet set = new SampleSet();
     foreach (var comp in compositions)
     {
         SampleSet songset = new SampleSet();
         //try
         // {
         songset = LoadSampleSetFromComposition(comp);
         // }
         //  catch (Exception e)
         //  {
         //      Console.WriteLine(e.Message);
         //  }
         set.AddAll(songset);
     }
     return set;
 }
Пример #11
0
        public static Composition LoadFromMIDI(string filename)
        {
            Composition comp = new Composition();
            comp.Tracks.Clear();

            NAudio.Midi.MidiFile f = new MidiFile(filename);

              //  if (f.Events.MidiFileType == 1)
               //     return LoadMidiType1(f);

            f.Events.MidiFileType = 0;

            byte max_channels = 0;
            foreach(var trackEvent in f.Events)
            foreach (var e in trackEvent)
                if (e.Channel > max_channels)
                    max_channels = (byte)e.Channel;
            max_channels++;
            Track[] tracks = new Track[max_channels];
            MelodySequence[] seqs = new MelodySequence[max_channels];
            TempoEvent[] tempos = new TempoEvent[max_channels];
            for (byte i = 0; i < max_channels; i++ )
            {
                tracks[i] = new Track(PatchNames.Acoustic_Grand, i);
                seqs[i] = new MelodySequence();
                tempos[i] = new TempoEvent((int)(Note.ToRealDuration((int)Durations.qn, 60) * 1000), 0);
                tempos[i].Tempo = 60;
            }
            foreach(var trackEvents in f.Events)
            foreach (var e in trackEvents)
            {
                if (e as TempoEvent != null)
                {
                    tempos[e.Channel] = (TempoEvent)e;
                }
                if (e as PatchChangeEvent != null)
                {
                    var p = e as PatchChangeEvent;
                    tracks[p.Channel].Instrument = (PatchNames)p.Patch;
                }
                NoteOnEvent on = e as NoteOnEvent;
                if (on != null && on.OffEvent != null)
                {
                    int total_dur = Note.ToNoteLength((int)on.AbsoluteTime, f.DeltaTicksPerQuarterNote, tempos[on.Channel].Tempo);
                    if (total_dur > seqs[on.Channel].Duration)
                        seqs[on.Channel].AddPause(total_dur - seqs[on.Channel].Duration);

                    int duration = Note.ToNoteLength(on.NoteLength, f.DeltaTicksPerQuarterNote, tempos[on.Channel].Tempo);
                    seqs[on.Channel].AddNote(new Note(on.NoteNumber, (int)duration));
                }
            }
            for(byte i = 0; i < max_channels; i++)
            {
                if(seqs[i].Length > 0)
                {
                    tracks[i].AddSequence(seqs[i]);
                    comp.Tracks.Add(tracks[i]);
                }
            }
            comp.NameTag = System.IO.Path.GetFileNameWithoutExtension(filename);
            return comp;
        }
Пример #12
0
        public void GenerateFromFiles(string path)
        {
            instruments = new Dictionary<PatchNames, MarkovChain<Note>>();
            Dictionary<PatchNames, List<string>> instrument_tracker = new Dictionary<PatchNames, List<string>>();
            //BinaryFormatter serializer = new BinaryFormatter();

            //System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Compress);
            int i = 0;
            var files = Utils.GetFiles(path);
            int percentage = files.Length / 100;
            //foreach (string f in files)
            Parallel.For(0, files.Length, j =>
            {
                bool continue_ = true;
                var f = files[j];
                if (System.IO.Path.GetExtension(f) != ".mid")
                    continue_ = false;
                var filename = System.IO.Path.GetFileNameWithoutExtension(f);
                Composition comp = new Composition();
                Console.WriteLine("{0:00.00}%\t Adding {1}", (float)i / files.Length * 100.0f, filename);
                try
                {
                    comp = Composition.LoadFromMIDI(f);
                }
                catch
                {
                    Console.WriteLine("Skipping {0}", filename);
                    continue_ = false;
                }
                List<int> instruments_ints = new List<int>();
                if (continue_)
                    foreach (var track in comp.Tracks)
                    {
                        instruments_ints.Add((int)track.Instrument);
                        var mel = track.GetMainSequence() as MelodySequence;
                        if (!instruments.ContainsKey(track.Instrument))
                        {
                            instruments[track.Instrument] = new MarkovChain<Note>(3);
                            instrument_tracker[track.Instrument] = new List<string>();
                        }
                        lock (instrument_tracker[track.Instrument])
                        {
                            instrument_tracker[track.Instrument].Add(filename);
                            instruments[track.Instrument].Add(mel.ToArray());
                        }
                    }

                //Report progress
                if (i > percentage)
                {
                    if (OnPercentage != null)
                        OnPercentage(this, i, 0);
                    percentage += files.Length / 100;
                }

                i++;
            });

            foreach (var k in instrument_tracker.Keys)
            {
                Console.WriteLine("Instrument {0} with count {1}", k, instrument_tracker[k].Count);
            }

            Save();

            Console.WriteLine("Done");
        }
Пример #13
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");
        }
Пример #14
0
        public float ComputeFitness(Composition comp)
        {
            var c = comp;
            if (MaxTracks > 0)
            {
                var newComp = new Composition();
                for (int k = 0; k < MaxTracks && k < comp.Tracks.Count; k++)
                {
                    newComp.Add(comp.Tracks[k]);
                }
                c = newComp;
            }

            string indi2str = c.ToString();

            return ComputeFitness(indi2str);
        }
Пример #15
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;
 }
Пример #16
0
 //IGenerator trackGenerator;
 public CompositionGenerator(Composition comp)
 {
     this.composition = comp;
     //this.trackGenerator = trackGenerator;
 }
Пример #17
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());
        }
Пример #18
0
        public void GenerateFromFiles(Composition[] compositions)
        {
            instruments = new Dictionary<PatchNames, MarkovChain<Note>>();
            instrument_tracker = new Dictionary<PatchNames, int>();

            int i = 0;

            int percentage = compositions.Length / 100;
            //foreach (string f in files)
            for(int j = 0; j < compositions.Length; j++)//Parallel.For(0, compositions.Length, j =>
            {
                Composition comp = compositions[j];
                Console.WriteLine("{0:00.00}%\t Adding {1}", (float)i / compositions.Length * 100.0f, comp.NameTag);

                List<int> instruments_ints = new List<int>();

                foreach (var track in comp.Tracks)
                {
                    instruments_ints.Add((int)track.Instrument);
                    var mel = track.GetMainSequence() as MelodySequence;
                    if (!instruments.ContainsKey(track.Instrument))
                    {
                        instruments[track.Instrument] = new MarkovChain<Note>(4);
                        instrument_tracker[track.Instrument] = 1;
                    }
                    lock (instruments[track.Instrument])
                    {
                        try
                        {
                            instrument_tracker[track.Instrument]++;
                        }
                        catch
                        { }
                        instruments[track.Instrument].Add(mel.ToArray());
                    }
                }

                //Report progress
                if (i > percentage)
                {
                    if (OnPercentage != null)
                        OnPercentage(this, i, 0);
                    percentage += compositions.Length / 100;
                }

                i++;
            }//);

            foreach (var k in instrument_tracker.Keys)
            {
                Console.WriteLine("Instrument {0} with count {1}", k, instrument_tracker[k]);
            }

            Save();

            Console.WriteLine("Done");
        }
Пример #19
0
 public CompositionRandomizer()
 {
     ActiveComposition = new Composition();
     generators = new List<INoteGenerator>();
     this.channelIndex = 1;
 }
Пример #20
0
 public CompositionCategory(string name, string path, Composition[] comps)
 {
     this.CategoryName = name;
     this.OriginalPath = path;
     this.Compositions = comps;
 }
Пример #21
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");
        }
Пример #22
0
        public SampleSet LoadSampleSetFromComposition(Composition comp)
        {
            SampleSet set = new SampleSet();

            if (comp.Tracks.Count < 2)
                return set;

            var mainSeq = comp.Tracks[0].GetMainSequence() as MelodySequence;
            var mainNotes = mainSeq.ToArray();

            for (int track = 1; track < comp.Tracks.Count; track++)
            {
                Dictionary<Note, int> frequencies = new Dictionary<Note, int>();

                if (comp.Tracks[track].Instrument != instrument)
                {
                   // Console.WriteLine("\tSkipping instrument {0}", comp.Tracks[track].Instrument);
                    continue;
                }

                var seq = comp.Tracks[track].GetMainSequence() as MelodySequence;
                var notes = seq.ToArray();

                var max = Math.Min(mainNotes.Length, notes.Length);

                if(seq.TotalNoteDuration() < seq.TotalRestDuration())
                {
                    continue;
                }

                Console.WriteLine("\tAdding instrument {0}", comp.Tracks[track].Instrument);

                for (int j = 0; j < max; j++ )
                {
                    if (!frequencies.ContainsKey(notes[j]))
                        frequencies[notes[j]] = 1;
                    else frequencies[notes[j]] += 1;
                }

               /* // Filtering
                for (int j = 0; j < max; j++)
                {
                    double normalizedFrequency = frequencies[notes[j]] / (double)max;
              //      if (normalizedFrequency < filterThreshold)
              //          continue;

                    if (notes[j].Velocity > 0)
                        notes[j].Velocity = 127;

                    if (!noteHashes.ContainsKey(notes[j]))
                        noteHashes[notes[j]] = hash++;
                }*/

                int mainTrackTime = 0;
                int accompTrackTime = 0;
                int incr = 0;
                for (int j = 0; j < max; j++)
                {
                    // make sure to use closest note
                    if (j + incr >= max)
                        break;
                 /*   mainTrackTime += mainNotes[j].Duration;
                    accompTrackTime += notes[j + incr].Duration;
                    while(accompTrackTime < mainTrackTime)
                    {
                        incr++;
                        if (j + incr + 1 > max)
                            break;
                        accompTrackTime += notes[j + incr].Duration;
                    }*/

                    if (j + incr > max - 1)
                        break;

            /*                    if (!noteHashes.ContainsKey(notes[j + incr]))
                        continue;

                    // caching notes
                    if (noteHashes[notes[j + incr]] > MAX_OUTPUTS - 1)
                        continue;
                    */

                    Sample s = GetSample(mainNotes[j],notes[j+incr]);

                    set.add(s);
                }

            }

            return set;
        }
Пример #23
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;
        }
Пример #24
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);
            }
        }
Пример #25
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;
 }
Пример #26
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);
 }
Пример #27
0
        public TrackGenerator(CompositionCategory category, Composition comp)
        {
            this.category = category;
            InitializeComponent();

            // Load data for accompany instruments
            string path = "save/" + category.CategoryName;
            if(System.IO.Directory.Exists(path))
            {
                var files = System.IO.Directory.GetFiles(path);
                foreach(var file in files)
                {
                    try
                    {
                        string filename = System.IO.Path.GetFileNameWithoutExtension(file);
                        if (!filename.ToLower().Contains("accomp_ann_ff_"))
                            continue;
                        var sub = filename.Substring(14);

                        PatchNames instrument = (PatchNames)(int.Parse(sub));

                        if(!accompInstruBox.Items.Contains(instrument))
                            accompInstruBox.Items.Add(instrument);
                    }
                    catch(Exception E)
                    {
                        Console.WriteLine(E);
                    }
                }
            }

            // Load data for accompany tracks
            if(comp != null)
                for(int i = 0; i < comp.Tracks.Count; i++)
                {
                    var track = comp.Tracks[i];

                    ComboBoxItem item = new ComboBoxItem();
                    item.Content = string.Format("Track {0} - {1}", i.ToString(), track.Instrument.ToString());
                    item.Tag = track;

                    accompTrackBox.Items.Add(item);
                }

            randomScale.Items.Clear();
            foreach(var s in Scales.ScaleTypes)
            {
                //ListBoxItem item = new ListBoxItem();
                randomScale.Items.Add(s);
            }

            randomInstrument.Items.Clear();
            var popularInstruments = new PatchNames[]{PatchNames.Acoustic_Grand,PatchNames.String_Ensemble_1,
                PatchNames.Acoustic_Bass,PatchNames.Trumpet,PatchNames.Violin,PatchNames.Electric_Grand,
                PatchNames.French_Horn,PatchNames.Flute,PatchNames.Trombone,PatchNames.Acoustic_Guitarnylon, PatchNames.Orchestral_Strings};
            foreach (var d in popularInstruments)
            {
                loadInstrument.Items.Add(d);
                geneticInstrumentBox.Items.Add(d);
                randomInstrument.Items.Add(d);
            }

            StopSpinner();

            LoadInstrumentalData();
        }