コード例 #1
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: SeparateTracks.exe filename.mid");
                Console.WriteLine("    filename.mid = MIDI file for which to generate code");
                Console.WriteLine();
                return;
            }

            if (!File.Exists(args[0]))
            {
                Console.WriteLine("Error: file {0} not found", args[0]);
                return;
            }

            try {
                MidiSequence sequence;
                using (Stream inputStream = File.OpenRead(args[0])) {
                    sequence = MidiSequence.Open(inputStream);
                }

                for (int i = 0; i < sequence.Tracks.Count; i++)
                {
                    MidiSequence newSequence = new MidiSequence(Format.Zero, sequence.Division);
                    newSequence.Tracks.Add(sequence.Tracks[i]);
                    using (Stream outputStream = File.OpenWrite(args[0] + "." + i + ".mid")) {
                        newSequence.Save(outputStream);
                    }
                }
            }
            catch (Exception exc) {
                Console.Error.WriteLine("Error: {0}", exc.Message);
            }
        }
コード例 #2
0
        /// <summary>Saves the sequence to a temporary file and returns the path to the file.</summary>
        /// <param name="sequence">The sequence to save.</param>
        /// <returns>The path to the temporary file where the sequence was saved.</returns>
        public static string SaveToTempFile(MidiSequence sequence)
        {
            string tmpPath = Path.GetTempFileName();

            using (var s = File.OpenWrite(tmpPath)) {
                sequence.Save(s);
            }
            return(tmpPath);
        }
コード例 #3
0
        public IEnumerable <string> Get()
        {
            //for (int i = 0; i < 10; i++)
            //{
            //    // get file location for saving and reading
            //    string saveLocation = Path.Combine(_env.ContentRootPath + "/Files/", "GOGOGOGO" + i + ".mid");

            //    // generate the midi sequence
            //    MidiSequence midi = RiffGenerator.RiffGenerator.Randomize("Track Name", 1000, GeneralMidiInstrument.AcousticGrand);

            //    // save to file
            //    using (Stream file = System.IO.File.Create(saveLocation))
            //    {
            //        midi.Save(file);
            //    }
            //}

            for (int i = 0; i < 10; i++)
            {
                // get file location for saving and reading

                string saveLocation = Path.Combine(_env.ContentRootPath + "/Files/", "breakdown" + i + ".mid");

                List <int> allowableOctaves = new List <int>()
                {
                    3
                };



                List <int> allowablePitches = new List <int>()
                {
                    8
                };
                List <int> allowableDurations = new List <int>()
                {
                    2, 3
                };

                // generate the midi sequence
                MidiSequence midi = RiffGenerator.RiffGenerator.Generate(allowableOctaves, allowablePitches, allowableDurations, "Track Name", 400, GeneralMidiInstrument.DistortionGuitar, new TimeSignature(4, 4), 140);

                // save to file
                using (Stream file = System.IO.File.Create(saveLocation))
                {
                    midi.Save(file);
                }
            }

            var users = _context.Users.ToList();

            return(new string[] { "value1", "value2" });
        }
コード例 #4
0
        static void Main(string [] args)
        {
            foreach (string midiFilename in args)
            {
                try
                {
                    // Open midi file
                    MidiSequence sequence = MidiSequence.Import(midiFilename);

                    // Spit out format info and ask for new format
                    int oldFormat = sequence.Format;
                    int newFormat = 0;

                    if (oldFormat != newFormat)
                    {
                        // Create the new midi file
                        MidiSequence newSequence = MidiSequence.Convert(
                            sequence, newFormat, MidiSequence.FormatConversionOptions.CopyTrackToChannel);

                        // Write out the new converted file
                        string newFilename = midiFilename + "." + newFormat + ".mid";
                        newSequence.Save(newFilename);

                        // Let the user know
                        Console.WriteLine("Converted {0}\r\n\tFrom type {1}\r\n\tTo type {2}\r\n\tSaved to {3}",
                                          midiFilename, oldFormat, newFormat, newFilename);
                    }
                    else
                    {
                        Console.WriteLine("File {0} is already type {1}.", midiFilename, newFormat);
                    }
                }
                catch (Exception exc)
                {
                    // Let the user know something went wrong
                    Console.WriteLine("Converting {0}\r\n\t{1}", midiFilename, exc.Message);
                }
            }

            Console.WriteLine("");
            Console.WriteLine("Hit enter to exit...");
            Console.ReadLine();
        }
コード例 #5
0
        void Output(OutputType type)
        {
            switch (type)
            {
            case OutputType.Midi:

                /*List<MidiEvent> midiEvents = new List<MidiEvent> ();
                 *
                 * double max = 0;
                 * for (int i = 0; i < notes.Count; i++) {
                 *      double d = notes[i].duration * 4;
                 *      double t1 = notes[i].time * 4;
                 *      double t2 = t1 + d;
                 *      max = t2 > max ? t2 : max;
                 *
                 *      NoteOnEvent note = new NoteOnEvent (Convert.ToInt64 (t1), 1, notes[i].noteNumber + 40, 127, Convert.ToInt32(d));
                 *      midiEvents.Add (note);
                 * }
                 * MidiEvent endMarker = new NoteEvent (Convert.ToInt64(max), 1, MidiCommandCode.StopSequence, 0, 0);
                 * midiEvents.Add (endMarker);
                 *
                 * MidiEventCollection collection = new MidiEventCollection (0, 1);
                 * collection.AddTrack (midiEvents);
                 *
                 * MidiFile.Export ("C:/Users/Jonas/OneDrive/GIP/Proef/Output/midi.mid", collection);*/

                MidiTrack track   = new MidiTrack();
                long      maxTime = 0;
                //string path = "C:/Users/Jonas/Desktop/result.txt";
                double previousTime = 0;
                for (int i = 0; i < notes.Count; i++)
                {
                    string path = "C:/Users/Jonas/Desktop/result.txt";
                    File.AppendAllText(path, string.Format("{0} at {1}\n", DecodeNote(notes[i].noteNumber + 44, NoteNotation.Short), notes[i].time));

                    double d  = 1;
                    double t1 = notes[i].time * 20 - previousTime;
                    double t2 = t1 + d;
                    if (t1 < 0)
                    {
                        continue;
                    }
                    previousTime = t2;



                    MidiEvent onEvent  = new OnNoteVoiceMidiEvent(Convert.ToInt64(t1), 1, (byte)(44 + notes[i].noteNumber), 63);
                    MidiEvent offEvent = new OffNoteVoiceMidiEvent(Convert.ToInt64(t2), 1, (byte)(44 + notes[i].noteNumber), 0);
                    long      t2long   = (long)t2;
                    maxTime = (t2long > maxTime) ? t2long : maxTime;

                    track.Events.Add(onEvent);
                    track.Events.Add(offEvent);
                }
                MidiEvent endMarker = new EndOfTrackMetaMidiEvent(maxTime);
                track.Events.Add(endMarker);
                MidiSequence sequence = new MidiSequence(Format.Zero, 1000);
                sequence.Tracks.Add(track);



                FileStream stream = new FileStream("C:/Users/Jonas/OneDrive/GIP/Proef/Output/midi.mid", FileMode.OpenOrCreate);
                sequence.Save(stream);
                stream.Close();
                break;

            case OutputType.Audio:
                double longest = 0;
                for (int i = 0; i < notes.Count; i++)
                {
                    double time = notes[i].time + notes[i].duration;
                    longest = Math.Max(time, longest);
                }
                double[] newSamples = new double[(int)Math.Ceiling(longest * rawAudio.sampleRate)];

                for (int i = 0; i < notes.Count; i++)
                {
                    int    startIndex = (int)Math.Floor(notes[i].time * rawAudio.sampleRate);
                    int    endIndex   = (int)Math.Floor((notes[i].time + notes[i].duration) * rawAudio.sampleRate);
                    double freq       = 110 * Math.Pow(1.059463094359295, notes[i].noteNumber);
                    double amp        = notes[i].amplitude;
                    for (int j = startIndex; j < endIndex; j++)
                    {
                        double time  = j * rawAudio.SampleLength + notes[i].time;
                        double value = Math.Sin(time * freq * 2 * Math.PI) * amp;
                        //double maxAmp = Math.Min (1, 5 * Math.Min (Math.Abs (time - notes[i].time), Math.Abs (time - (notes[i].time + notes[i].duration))));
                        newSamples[j] += value;
                    }
                }
                for (int i = 0; i < newSamples.Length; i++)
                {
                    newSamples[i] = Math.Max(Math.Min(1, newSamples[i]), -1);
                }
                int      avgSpread     = 35;
                double[] smoothSamples = new double[newSamples.Length - avgSpread];
                for (int i = 0; i < newSamples.Length - avgSpread; i++)
                {
                    double tot = 0;
                    for (int j = 0; j < avgSpread; j++)
                    {
                        tot += newSamples[i + j];
                    }
                    smoothSamples[i] = tot / avgSpread;
                }
                Song song = new Song(smoothSamples, rawAudio.channels, rawAudio.sampleRate);

                // GIPIO.SaveSong (song, GIPIO.outputPath + "test.wav");
                producedAudio = song;
                break;

            case OutputType.Wavelet:
                pixels = new uint[allAmps.Count * allAmps[0].Length];
                for (int x = 0; x < allAmps.Count; x++)
                {
                    for (int y = 0; y < allAmps[0].Length; y++)
                    {
                        double i = allAmps[x][y];
                        // i *= 2;
                        i = Math.Min(1, i);
                        // double r = -2 * (i - 1.0) * (2 * (i - 1.0)) + 1;
                        // double g = -2 * (i - 0.5) * (2 * (i - 0.5)) + 1;
                        // double b = -2 * (i - 0.0) * (2 * (i - 0.0)) + 1;

                        double r, g, b;
                        r = g = b = i;

                        uint red   = (uint)Math.Round(r * 255);
                        uint green = (uint)Math.Round(g * 255);
                        uint blue  = (uint)Math.Round(b * 255);

                        int index = (allAmps[0].Length - y - 1) * allAmps.Count + x;
                        pixels[index] = (uint)((255 << 24) + (red << 16) + (green << 8) + blue);
                    }
                }
                DrawWavelet();

                break;
            }
        }
コード例 #6
0
        static void Main(string[] args)
        {
            int[] codeMidi = new int[] { 0, 0, 0, 0, 0, 0, 0 };
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: TransposeMidi.exe filename.mid steps");
                Console.WriteLine("    filename.mid = MIDI file to be transposed");
                Console.WriteLine("    steps = Number of steps to transpose, positive or negative");
                Console.WriteLine();
                return;
            }

            string originpath = System.IO.Directory.GetCurrentDirectory();

            string[] op = originpath.Split('\\');
            originpath = "";
            for (int i = 0; i < (op.Length) - 4; i++)
            {
                originpath += op[i];
                originpath += "\\";
            }



            if (!File.Exists(args[0]))
            {
                Console.WriteLine("Error: file {0} not found", args[0]);
                return;
            }

            /*            int steps;
             *          if (!int.TryParse(args[1], out steps))
             *          {
             *              Console.WriteLine("Error: invalid number of steps {0}", args[1]);
             *              return;
             *          }*/

            try
            {
                MidiSequence sequence;
                using (Stream inputStream = File.OpenRead(args[0]))
                {
                    sequence = MidiSequence.Open(inputStream);
                }



                for (int i = 0; i < 8; i++)
                {
                    MidiSequence newSequence = sequence.Trim(1857 * i, 1857 * (i + 1) + 10);
                    //              sequence.Transpose(steps);

                    using (Stream outputStream = File.OpenWrite(originpath + @"\\toUnity\\" + i + "\\" + "originmelody." + i + ".trimed.mid.txt"))
                    {
                        newSequence.Save(outputStream);
                    }
                    foreach (MidiTrack track in newSequence)
                    {
                        for (int j = 1; j < track.Events.Count - 1; j = j + 2)
                        {
                            //Console.WriteLine(track.Events[i].ToString().IndexOf("G4"));
                            //Console.WriteLine(track.Events[i].ToString());
                            //Console.WriteLine(track.Events[i].ToString().Substring(5,7));

                            char     spt      = '\t';
                            string[] spstring = track.Events[j].ToString().Split(spt);

                            switch (spstring[2])
                            {
                            case "C6": codeMidi[2] = codeMidi[2] + 3; codeMidi[5] = codeMidi[5] + 2; codeMidi[0]++; break;

                            case "D6": codeMidi[3] = codeMidi[3] + 3; codeMidi[6] = codeMidi[6] + 2; codeMidi[1]++; break;

                            case "E6": codeMidi[4] = codeMidi[4] + 3; codeMidi[0] = codeMidi[0] + 2; codeMidi[2]++; break;

                            case "F6": codeMidi[5] = codeMidi[5] + 3; codeMidi[1] = codeMidi[1] + 2; codeMidi[3]++; break;

                            case "G6": codeMidi[6] = codeMidi[6] + 3; codeMidi[2] = codeMidi[2] + 2; codeMidi[4]++; break;

                            case "A6": codeMidi[0] = codeMidi[0] + 3; codeMidi[5] = codeMidi[5] + 2; codeMidi[3]++; break;

                            case "B6": codeMidi[1] = codeMidi[1] + 3; codeMidi[6] = codeMidi[5] + 2; codeMidi[4]++; break;

                            default: break;
                            }

                            //Console.WriteLine(spstring[2]);
                        }
                        int maxValue = codeMidi.Max();

                        String        path    = System.IO.Directory.GetCurrentDirectory() + @"\\toUnity\\" + i;
                        DirectoryInfo dirInfo = new DirectoryInfo(path);
                        if (dirInfo.Exists == false)
                        {
                            Directory.CreateDirectory(path);
                        }

                        for (int j = 0; j < 8; j++)
                        {
                            if (codeMidi[j] == maxValue)
                            {
                                //Console.WriteLine(j);

                                List <String> MyFiles = Directory.GetFiles(originpath + @"\Resources\\" + j).ToList();

                                foreach (string file in MyFiles)
                                {
                                    FileInfo mFile = new FileInfo(file);
                                    // to remove name collisions
                                    if (new FileInfo(originpath + @"\\toUnity\\" + i + "\\" + mFile.Name).Exists == false)
                                    {
                                        mFile.CopyTo(originpath + @"\\toUnity\\" + i + "\\" + mFile.Name + ".txt");
                                    }
                                }
                                MyFiles.Clear();
                                MyFiles = null;
                                break;
                            }
                        }
                        System.Array.Clear(codeMidi, 0, 7);
                    }
                }
            }



            /*string outputPath = args[0] + ".transposed.mid";
             * using (Stream outputStream = File.OpenWrite(outputPath)) {
             *  sequence.Save(outputStream);
             * }
             * Console.WriteLine("Transposed MIDI written to: {0}", outputPath);*/
            //

            catch (Exception exc)
            {
                Console.Error.WriteLine("Error: {0}", exc.Message);
            }
        }
コード例 #7
0
        public Stream Flip(Stream midiFile, int octaveChangeOption)
        {
            //Load midi file
            MidiSequence midi = MidiSequence.Open(midiFile);

            //The anchor note to flip everything else around
            float anchorNote = midi.Tracks
                               .Where(t => t.Events.OfType <NoteVoiceMidiEvent>().Any() && t.Events.OfType <NoteVoiceMidiEvent>().Any(n => n.Channel != 9 && n.Channel != 10))
                               .Select(t => t.Events.OfType <NoteVoiceMidiEvent>().First())
                               .OrderBy(e => e.DeltaTime).GroupBy(e => e.DeltaTime).First() //Find the first note
                               .Min(e => e.Note);                                           //Order by note number if there are notes playing at the same time

            int highestNote = midi.Tracks
                              .Where(t => t.Events.OfType <NoteVoiceMidiEvent>().Any(n => n.Channel != 9 && n.Channel != 10))
                              .SelectMany(t => t.Events.OfType <NoteVoiceMidiEvent>())
                              .Max(e => e.Note);
            int lowestNote = midi.Tracks
                             .Where(t => t.Events.OfType <NoteVoiceMidiEvent>().Any(n => n.Channel != 9 && n.Channel != 10))
                             .SelectMany(t => t.Events.OfType <NoteVoiceMidiEvent>())
                             .Min(e => e.Note);

            int octaveChange = 0; //Global octave change required for this sequence

            octaveChangeOption *= Constants.Octave;

            bool flipFromMiddle = false; //If octave changes aren't possible, sequence needs to be flipped around the middle

            //Check if flipping won't make the notes go out of range (0-127) TODO: Test all cases
            if (anchorNote - lowestNote > highestNote - anchorNote)
            {
                //Flipping might make notes go past 127, if so, try to decrease octave
                float outOfRange = anchorNote + (anchorNote - lowestNote);

                if (outOfRange > Constants.MaxMidiNote)
                {
                    while (outOfRange + octaveChange > Constants.MaxMidiNote)
                    {
                        octaveChange -= Constants.Octave;
                    }

                    if (lowestNote + octaveChange < Constants.MinMidiNote)
                    {
                        //Out of range on the other side now, flip everything around the middle note instead and don't change octave
                        flipFromMiddle = true;
                        octaveChange   = 0;
                    }
                }
            }
            else
            {
                //Flipping might make notes go below 0, if so, try to increase octave
                float outOfRange = anchorNote - (highestNote - anchorNote);

                if (outOfRange < Constants.MinMidiNote)
                {
                    while (outOfRange + octaveChange < Constants.MinMidiNote)
                    {
                        octaveChange += Constants.Octave;
                    }

                    if (highestNote + octaveChange > Constants.MaxMidiNote)
                    {
                        //Out of range on the other side now, flip everything around the middle note instead and don't change octave
                        flipFromMiddle = true;
                        octaveChange   = 0;
                    }
                }
            }

            if (flipFromMiddle) //Changing octaves is not possible, flip everything around the middle
            {
                anchorNote = (float)(highestNote - lowestNote) / 2;
            }

            //Flip all notes
            foreach (MidiTrack track in midi.Tracks)
            {
                IEnumerable <NoteVoiceMidiEvent> noteEvents = track.OfType <NoteVoiceMidiEvent>().Where(n => n.Channel != 9 && n.Channel != 10);

                if (!noteEvents.Any())
                {
                    continue;                    //Nothing to flip
                }
                foreach (NoteVoiceMidiEvent onNoteEvent in noteEvents)
                {
                    onNoteEvent.Note = (byte)(anchorNote + anchorNote - onNoteEvent.Note + octaveChange + octaveChangeOption);
                }
            }

            //Create flipped MIDI-file
            Stream flippedMidiStream = new MemoryStream();

            midi.Save(flippedMidiStream);
            flippedMidiStream.Position = 0;

            return(flippedMidiStream);
        }