Exemplo n.º 1
0
        static void Main(string[] args)
        {
            // override default local culture settings
            var englishCulture = CultureInfo.CreateSpecificCulture("en-US");

            CultureInfo.CurrentCulture   = englishCulture;
            CultureInfo.CurrentUICulture = englishCulture;

            Console.WriteLine("Testing Composition Services...");

            // midi (playback) file path
            string filePath = ConfigurationManager.AppSettings["midiFile"];

            // chords file path
            string chordsFilePath = ConfigurationManager.AppSettings["chordsFile"];

            // source files for testing
            string filePathTest   = ConfigurationManager.AppSettings["midiFileTest"];
            string chordsPathTest = ConfigurationManager.AppSettings["chordsFileTest"];

            // set the strategy compositor
            CompositionStrategy compositionStrategy = CompositionStrategy.GeneticAlgorithmStrategy;

            MelodyEvaluatorsWeights evaluatorsWeights = new MelodyEvaluatorsWeights
            {
                AccentedBeats    = 30,
                ContourDirection = 10,
                ContourStability = 15,
                DensityBalance   = 15,
                ExtremeIntervals = 25,
                PitchRange       = 15,
                PitchVariety     = 15,
                SmoothMovement   = 20,
                Syncopation      = 20
            };


            // create a new composition with injected strategy
            CompositionContext compositionContext = new CompositionContext(chordsFilePath, filePath, melodyTrackIndex: MelodyTrackIndex.TrackNumber1);

            IMidiFile[] newMidiFiles = compositionContext.Compose(
                compositionStrategy,
                musicalInstrument: MusicalInstrument.ElectricGrandPiano,
                overallNoteDurationFeel: OverallNoteDurationFeel.Intense,
                pitchRangeSource: PitchRangeSource.Custom,
                minPitch: NotePitch.C3,
                maxPitch: NotePitch.G6,
                useExistingMelodyAsSeed: false,
                customParams: evaluatorsWeights);

            IMidiFile[] bestCompositions = newMidiFiles.Take(10).ToArray();
            for (int i = 0; i < bestCompositions.Count(); i++)
            {
                bestCompositions[i].SaveFile(fileNamePrefix: $"consoleTest_{i+1}_");
            }

            bestCompositions.FirstOrDefault()?.FadeOut();
            bestCompositions.FirstOrDefault()?.Play();
        }
Exemplo n.º 2
0
        private void btnCompose_Click(object sender, EventArgs e)
        {
            var composition = new CompositionContext(_chordsFilePath, _midiFilePath, melodyTrackIndex: MelodyTrackIndex.TrackNumber1);
            var newMelody   = composition.Compose(musicalInstrument: _musicalInstrument);

            composition.MidiOutputFile.SaveFile();
            composition.MidiOutputFile.PlayAsync();
            var res = MessageBox.Show("Want to pause?", "Playing", MessageBoxButtons.YesNoCancel);

            if (res == DialogResult.Yes)
            {
                composition.MidiOutputFile.Stop();
            }
        }
Exemplo n.º 3
0
        private void btnUploadChords_Click(object sender, EventArgs e)
        {
            if (_chordsFileDialog.ShowDialog() == DialogResult.OK)
            {
                _chordsFilePath = _chordsFileDialog.FileName;
                _chordsFileName = _chordsFileDialog.SafeFileName;

                lblChordsFileName.Text = _chordsFileName;

                if (!string.IsNullOrWhiteSpace(_chordsFilePath) && !string.IsNullOrWhiteSpace(_midiFilePath))
                {
                    _composition               = new CompositionContext(_chordsFilePath, _midiFilePath, melodyTrackIndex: MelodyTrackIndex.TrackNumber1);
                    _midiFile                  = _composition.Compose()[0];
                    lblMidiTitle.Text         += ": " + _midiFile.Title;
                    lblMidiBpm.Text           += ": " + _midiFile.BeatsPerMinute.ToString();
                    lblMidiTimeSignature.Text += ": " + _midiFile.KeySignature.ToString();
                    lblMidiBars.Text          += ": " + _midiFile.NumberOfBars.ToString();
                }
            }
        }
Exemplo n.º 4
0
        public async Task <ActionResult> Compose(CompositionViewModel model)
        {
            // validate that sum of weights is equal to 100
            double weightSum = model.WeightSum;

            if (weightSum != 100)
            {
                string errorMessage =
                    $"The total weights of all fitness function " +
                    $"evaluators must sum up to 100.\n" +
                    $"The current sum is {weightSum}";
                this.ModelState.AddModelError(nameof(model.AccentedBeats), errorMessage);
            }

            // assure all other validations passed okay
            if (!ModelState.IsValid)
            {
                CompositionViewModel viewModel = new CompositionViewModel
                {
                    SongSelectList  = new SelectList(_databaseGateway.Songs.GetAll().OrderBy(s => s.Title), nameof(Song.Id), nameof(Song.Title)),
                    PitchSelectList = new SelectList(_pitchSelectList, nameof(PitchRecord.Pitch), nameof(PitchRecord.Description)),
                };
                return(View(viewModel));
            }

            // fetch song from datasource
            Song song = _databaseGateway.Songs.Get(model.SongId);

            // get the chord and file paths on the file server
            string chordFilePath = await SongsController.GetSongPath(song.Id, _databaseGateway, User, SongFileType.ChordProgressionFile);

            string midiFilePath = await SongsController.GetSongPath(song.Id, _databaseGateway, User, SongFileType.MidiOriginalFile);

            // create a compositon instance
            CompositionContext composition = new CompositionContext(
                chordProgressionFilePath: chordFilePath,
                midiFilePath: midiFilePath,
                melodyTrackIndex: song.MelodyTrackIndex);

            // build evaluators weights
            MelodyEvaluatorsWeights weights = new MelodyEvaluatorsWeights
            {
                AccentedBeats    = model.AccentedBeats,
                ContourDirection = model.ContourDirection,
                ContourStability = model.ContourStability,
                DensityBalance   = model.DensityBalance,
                ExtremeIntervals = model.ExtremeIntervals,
                PitchRange       = model.PitchRange,
                PitchVariety     = model.PitchVariety,
                SmoothMovement   = model.SmoothMovement,
                Syncopation      = model.Syncopation
            };

            // Compose some melodies and fetch the best one
            IMidiFile midiFile = composition.Compose(
                strategy: CompositionStrategy.GeneticAlgorithmStrategy,
                overallNoteDurationFeel: model.OverallNoteDurationFeel,
                musicalInstrument: model.MusicalInstrument,
                minPitch: model.MinPitch,
                maxPitch: model.MaxPitch,
                useExistingMelodyAsSeed: model.useExistingMelodyAsSeed,
                customParams: weights)
                                 .FirstOrDefault();

            // save the midifile output internally
            _midiFile        = midiFile;
            ViewBag.MidiFile = midiFile;

            // save file on the file server
            string directoryPath = HomeController.GetFileServerPath() + "Outputs" +
                                   Path.DirectorySeparatorChar + song.Id + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(directoryPath);
            string filePath = _midiFile.SaveFile(outputPath: directoryPath);

            // return the file to the client client for downloading
            string fileName = Path.GetFileName(filePath);

            byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
            return(File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName));
        }