예제 #1
0
파일: Program.cs 프로젝트: cwelt/Soloist
        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();
        }
예제 #2
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));
        }