Ejemplo n.º 1
0
    public MeltySynthTest(bool enableEffects)
    {
        soundFont = new SoundFont(Settings.SoundFontPath);
        midiFile  = new MidiFile(Settings.MidiFilePath);

        var settings = new SynthesizerSettings(Settings.SampleRate);

        settings.EnableReverbAndChorus = enableEffects;
        settings.MaximumPolyphony      = 40;

        synthesizer = new Synthesizer(soundFont, settings);
        sequencer   = new MidiFileSequencer(synthesizer);

        sequencer.Play(midiFile, true);

        left        = new float[Settings.BlockSize];
        right       = new float[Settings.BlockSize];
        writeBuffer = new float[2 * Settings.BlockSize];

        var name = enableEffects ? "meltysynth_output.wav" : "meltysynth_output_noeffect.wav";

        if (Settings.OutputFile)
        {
            writer = new NAudioSampleWriter(name, Settings.WaveFormat);
        }
        else
        {
            writer = new NullSampleWriter();
        }
    }
Ejemplo n.º 2
0
        public void Awake()
        {
            synthesizer = new Synthesizer(sampleRate, channel, bufferSize, 1);
            sequencer   = new MidiFileSequencer(synthesizer);
            audioSource = GetComponent <AudioSource>();
            midiSource.streamingAssetPath = CurrentMidi.path + CurrentMidi.currentMidiTitle;
            bankSource.streamingAssetPath = Application.streamingAssetsPath + "/CSharpSynth/" + CurrentMidi.currentSoundbankTitle;

            if (loadOnAwake)
            {
                LoadBank(new PatchBank(bankSource));
                LoadMidi(new MidiFile(midiSource));
            }

            if (playOnAwake)
            {
                Play();
            }

            for (int i = 0; i < instruments.Length; i++)
            {
                AddNote(i, instruments[i]);
            }

            foreach (Transform i in instruments)
            {
                i.gameObject.SetActive(false);
            }

            endZone.position += new Vector3(0, 0, midi.Tracks[0].MidiEvents.Length + 50);
        }
Ejemplo n.º 3
0
 public SynthThread()
 {
     synth          = new Synthesizer(Properties.Settings.Default.SampleRate, 2, Properties.Settings.Default.BufferSize, Properties.Settings.Default.BufferCount, Properties.Settings.Default.poly);
     mseq           = new MidiFileSequencer(synth);
     synth_provider = new SynthWaveProvider(synth, mseq);
     direct_out     = new DirectSoundOut(Properties.Settings.Default.Latency);
     direct_out.Init(synth_provider);
 }
Ejemplo n.º 4
0
            public void ProcessMidiEvents(Synthesizer synthesizer)
            {
                if (sequencer == null)
                {
                    sequencer = new MidiFileSequencer(synthesizer);
                    sequencer.Play(midi, loop);
                }

                sequencer.ProcessEvents();
            }
Ejemplo n.º 5
0
            public void RenderWaveform(Synthesizer synthesizer, Span <float> left, Span <float> right)
            {
                if (sequencer == null)
                {
                    sequencer = new MidiFileSequencer(synthesizer);
                    sequencer.Play(midi, loop);
                }

                sequencer.Render(left, right);
            }
        private bool InitSynth()
        {
            // Get peer AudioSource
            audioSource = GetComponent <AudioSource>();
            if (audioSource == null)
            {
                DaggerfallUnity.LogMessage("DaggerfallSongPlayer: Could not find AudioSource component.");
                return(false);
            }

            // Create synthesizer and load bank
            if (midiSynthesizer == null)
            {
                // Get number of channels
                if (AudioSettings.driverCapabilities.ToString() == "Mono")
                {
                    channels = 1;
                }
                else
                {
                    channels = 2;
                }

                // Create synth
                AudioSettings.GetDSPBufferSize(out bufferLength, out numBuffers);
                midiSynthesizer = new Synthesizer(sampleRate, channels, bufferLength / numBuffers, numBuffers, polyphony);

                // Load bank data
                byte[] bankData = LoadBank(SoundBank);
                if (bankData == null)
                {
                    return(false);
                }
                else
                {
                    midiSynthesizer.LoadBank(new MyMemoryFile(bankData, SoundBank));
                    midiSynthesizer.ResetSynthControls(); // Need to do this for bank to load properly, don't know why
                }
            }

            // Create sequencer
            if (midiSequencer == null)
            {
                midiSequencer = new MidiFileSequencer(midiSynthesizer);
            }

            // Check init
            if (midiSynthesizer == null || midiSequencer == null)
            {
                DaggerfallUnity.LogMessage("DaggerfallSongPlayer: Failed to init synth.");
                return(false);
            }

            return(true);
        }
Ejemplo n.º 7
0
        public SynthWaveProvider(Synthesizer synth, MidiFileSequencer mseq)
        {
            this.synth = synth;
            this.mseq  = mseq;
            waveFormat = new WaveFormat(synth.SampleRate, 16, synth.AudioChannels);
            int bufferSize = (int)Math.Ceiling((2.0 * waveFormat.AverageBytesPerSecond) / synth.RawBufferSize) * synth.RawBufferSize;

            circularBuffer = new CircularBuffer(bufferSize);
            sbuff          = new byte[synth.RawBufferSize];
            state          = PlayerState.Stopped;
        }
Ejemplo n.º 8
0
            public void FillBuffer(Synthesizer synthesizer)
            {
                if (sequencer == null)
                {
                    sequencer = new MidiFileSequencer(synthesizer);
                    sequencer.LoadMidi(midi);
                    sequencer.Play();
                }

                sequencer.FillMidiEventQueue(loop);
                synthesizer.GetNext();
            }
Ejemplo n.º 9
0
            public void FillBuffer(Synthesizer synthesizer)
            {
                if (this.sequencer == null)
                {
                    this.sequencer = new MidiFileSequencer(synthesizer);
                    this.sequencer.LoadMidi(this.midi);
                    this.sequencer.Play();
                }

                this.sequencer.FillMidiEventQueue(this.loop);
                synthesizer.GetNext();
            }
Ejemplo n.º 10
0
        public void Awake()
        {
            synthesizer = new Synthesizer(sampleRate, channel, bufferSize, 1);
            sequencer   = new MidiFileSequencer(synthesizer);
            audioSource = GetComponent <AudioSource>();

            if (loadOnAwake)
            {
                LoadBank(new PatchBank(bankSource));
                LoadMidi(new MidiFile(midiSource));
            }

            if (playOnAwake)
            {
                Play();
            }
        }
Ejemplo n.º 11
0
            public MidiSoundStream(string soundFontPath, int sampleRate)
            {
                synthesizer = new Synthesizer(soundFontPath, sampleRate);
                left        = new float[synthesizer.BlockSize];
                right       = new float[synthesizer.BlockSize];

                sequencer = new MidiFileSequencer(synthesizer);

                var blockDuration = (double)synthesizer.BlockSize / synthesizer.SampleRate;

                blocksPerBatch = (int)Math.Ceiling(0.05 / blockDuration);
                batchLength    = synthesizer.BlockSize * blocksPerBatch;
                batch          = new short[2 * batchLength];

                mutex = new object();

                Initialize(2, (uint)sampleRate);

                Volume = 50;
            }
Ejemplo n.º 12
0
    public CSharpSynthTest()
    {
        midiFile = new MidiFile(Settings.MidiFilePath);

        synthesizer = new Synthesizer(Settings.SampleRate, 2, Settings.BlockSize, 1);
        synthesizer.LoadBank(Settings.SoundFontPath);
        sequencer = new MidiFileSequencer(synthesizer);

        sequencer.LoadMidi(midiFile);
        sequencer.Play();

        if (Settings.OutputFile)
        {
            writer = new NAudioSampleWriter("csharpsynth_output.wav", Settings.WaveFormat);
        }
        else
        {
            writer = new NullSampleWriter();
        }
    }
Ejemplo n.º 13
0
        public void Awake()
        {
            if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                sampleRate = 24000;
            }
            synthesizer = new Synthesizer(sampleRate, channel, bufferSize, 1);
            sequencer   = new MidiFileSequencer(synthesizer);
            audioSource = GetComponent <AudioSource> ();

            if (loadOnAwake)
            {
                LoadBank(new PatchBank(bankSource));
                //LoadMidi (new MidiFile (midiSource));
            }

            if (playOnAwake)
            {
                //Play ();
            }
        }
Ejemplo n.º 14
0
        public SynthPlayer()
        {
            Logger.Debug("Initializing player");

            State = SynthPlayerState.Stopped;
            OnPlayerStateChanged(new PlayerStateChangedEventArgs(State));

            Logger.Debug("Opening output");
            Output = Platform.Platform.CreateOutput();

            Logger.Debug("Creating synthesizer");
            Synth     = new Synthesizer(Output.SampleRate, SynthConstants.AudioChannels, 441, 3, 100);
            Sequencer = new MidiFileSequencer(Synth);

            Sequencer.AddFinishedListener(Output.SequencerFinished);

            Output.Finished += () =>
            {
                // stop everything
                Stop();
                Logger.Debug("Finished playback");
                OnFinished();
            };
            Output.SampleRequest += () =>
            {
                // synthesize buffer
                Sequencer.FillMidiEventQueue();
                Synth.Synthesize();
                // send it to output
                Output.AddSamples(Synth.SampleBuffer);
            };
            Output.PositionChanged += pos =>
            {
                // log position
                FirePositionChanged(pos);
            };

            Output.Open();
        }
Ejemplo n.º 15
0
    public void LoadMidi(MidiFile file)
    {
        MidiFileSequencer sequencer = new MidiFileSequencer(new Synthesizer(44100, 2, 1024, 1)); //temporary needs changed

        sequencer.Stop();
        sequencer.UnloadMidi();
        sequencer.LoadMidi(file);

        midiMessages = sequencer.getData();
        division     = file.Division;

        //-------------------parsing midi
        var currentPosition = 0f;
        var previousDelta   = 0f;

        foreach (var message in midiMessages)
        {
            /*var delta = (message.delta - previousDelta);
             * currentPosition += delta;
             * previousDelta += delta;*/

            var delta = message.originalDelta;
            currentPosition += delta;

            for (int i = 0; i < currentlyDrawing.Count; i++)
            {
                currentlyDrawing[i].length += delta;
            }
            if ((int)message.command == 0x80 || ((int)message.command == 0x90 && message.data2 == 0))
            {
                var noteToStop = currentlyDrawing.Find(item => item.key == (message.data1 - 21));
                if (noteToStop != null)
                {
                    Draw(noteToStop, magnitude);
                    currentlyDrawing.Remove(noteToStop);
                }
            }
            else if ((int)message.command == 0x90)
            {
                var toAdd = new pianoNote()
                {
                    length   = 0f,
                    velocity = message.data2,
                    key      = (int)message.data1 - 21,
                    heightPositionOnScreen = currentPosition
                };
                currentlyDrawing.Add(toAdd);
            }
            if ((int)message.command == 0xFF && message.data1 == 0x51)
            {
                //throw TEMPO CHANGED EVENT
                Debug.Log($"BPM: {message.BPM}");
            }
        }
        //-------------------------------


        //trigger midi loaded event so that any listeners can have access to the midi file division
        TempoChangedEventArgs args = new TempoChangedEventArgs(120, magnitude);

        MidiLoaded?.Invoke(this, args);
    }
Ejemplo n.º 16
0
        private bool InitSynth()
        {
            // Get peer AudioSource
            audioSource = GetComponent<AudioSource>();
            if (audioSource == null)
            {
                DaggerfallUnity.LogMessage("DaggerfallSongPlayer: Could not find AudioSource component.");
                return false;
            }

            // Create synthesizer and load bank
            if (midiSynthesizer == null)
            {
                // Get number of channels
                if (AudioSettings.driverCapabilities.ToString() == "Mono")
                    channels = 1;
                else
                    channels = 2;

                // Create synth
                AudioSettings.GetDSPBufferSize(out bufferLength, out numBuffers);
                midiSynthesizer = new Synthesizer(sampleRate, channels, bufferLength / numBuffers, numBuffers, polyphony);

                // Load bank data
                byte[] bankData = LoadBank(SoundBank);
                if (bankData == null)
                    return false;
                else
                {
                    midiSynthesizer.LoadBank(new MyMemoryFile(bankData, SoundBank));
                    midiSynthesizer.ResetSynthControls(); // Need to do this for bank to load properly, don't know why
                }
            }

            // Create sequencer
            if (midiSequencer == null)
                midiSequencer = new MidiFileSequencer(midiSynthesizer);

            // Check init
            if (midiSynthesizer == null || midiSequencer == null)
            {
                DaggerfallUnity.LogMessage("DaggerfallSongPlayer: Failed to init synth.");
                return false;
            }

            return true;
        }
        private bool InitSynth()
        {
            // Get peer AudioSource
            audioSource = GetComponent <AudioSource>();
            if (audioSource == null)
            {
                DaggerfallUnity.LogMessage("DaggerfallSongPlayer: Could not find AudioSource component.");
                return(false);
            }

            // Create synthesizer and load bank
            if (midiSynthesizer == null)
            {
                // Get number of channels
                if (AudioSettings.driverCapabilities.ToString() == "Mono")
                {
                    channels = 1;
                }
                else
                {
                    channels = 2;
                }

                // Create synth
                AudioSettings.GetDSPBufferSize(out bufferLength, out numBuffers);
                midiSynthesizer = new Synthesizer(sampleRate, channels, bufferLength / numBuffers, numBuffers, polyphony);

                // Load bank data
                string filename = DaggerfallUnity.Settings.SoundFont;
                byte[] bankData = LoadBank(filename);
                if (bankData == null)
                {
                    // Attempt to fallback to default internal soundfont
                    bankData = LoadDefaultSoundFont();
                    filename = defaultSoundFontFilename;
                    Debug.LogFormat("Using default SoundFont {0}", defaultSoundFontFilename);
                }
                else
                {
                    Debug.LogFormat("Trying custom SoundFont {0}", filename);
                }

                // Assign to synth
                if (bankData == null)
                {
                    return(false);
                }
                else
                {
                    midiSynthesizer.LoadBank(new MyMemoryFile(bankData, filename));
                    midiSynthesizer.ResetSynthControls(); // Need to do this for bank to load properly, don't know why
                }
            }

            // Create sequencer
            if (midiSequencer == null)
            {
                midiSequencer = new MidiFileSequencer(midiSynthesizer);
            }

            // Check init
            if (midiSynthesizer == null || midiSequencer == null)
            {
                DaggerfallUnity.LogMessage("DaggerfallSongPlayer: Failed to init synth.");
                return(false);
            }

            return(true);
        }
Ejemplo n.º 18
0
        public void SaveScoresAndViewFeedback(MidiSessionDto session, bool save = true)
        {
            var userEvents  = session.userNoteDurations;
            var trackEvents = session.trackNoteDurations;

            Debug.Log("User events: " + userEvents.Count());
            Debug.Log("Track events: " + trackEvents.Count());

            var segments = MakeSegmentsFor(userEvents, trackEvents);
            var velocity = 1f / session.velocityIn * session.noteScale;
            var total    = 0d;
            var correct  = 0d;

            if (userEvents.Count == 0)
            {
                Debug.LogWarning("No midievents recorded");
            }

            foreach (var e in segments)
            {
                var keyNum = e.Key;
                var list   = e.Value;

                foreach (var m in list)
                {
                    var key = PianoKeys.GetKeyFor(keyNum);
                    total++;
                    var go      = Instantiate(cube);
                    var lmraway = piano.GetLMRAwayVectorsForKey(key,
                                                                MidiFileSequencer.calcX(m.offsetY / velocity + m.scaleY / 2f / velocity));
                    spawnedSegments.Add(go);
                    var dummy = new GameObject();
                    var k     = piano.GetKeyObj(key);
                    dummy.transform.SetParent(k.transform);
                    go.transform.SetParent(piano.transform);
                    var dropdownScale = go.transform.localScale;
                    go.transform.localScale = new Vector3(dropdownScale.x, m.scaleY / velocity, dropdownScale.z);
                    go.transform.position   = lmraway.away;

                    Color color;
                    switch (m.type)
                    {
                    case MidiSegment.SegmentType.EXTRA:
                        color = Color.red;
                        go.transform.localScale += new Vector3(.0001f, .0001f, .0001f);
                        break;

                    case MidiSegment.SegmentType.CORRECT:
                        color = Color.green;
                        go.transform.localScale += new Vector3(.0002f, .0002f, .0002f);
                        correct++;
                        break;

                    case MidiSegment.SegmentType.MISSED:
                        color = Color.yellow;
                        break;

                    default:
                        color = Color.black;     // WTF C#??
                        break;
                    }

                    var rder = go.GetComponent <Renderer>();
                    rder.material.color = color;
                    var rotation = Quaternion.LookRotation(lmraway.centre - lmraway.away);
                    go.transform.rotation = rotation;
                    go.transform.Rotate(0, -90f, 90f);
                }
            }

            var accuracy = correct / total;

            Debug.Log("Displaying end feedback text");
            int score;

            if (save)
            {
                score = (int)(accuracy * 100);
            }
            else
            {
                score = (int)(session.Accuracy * 100);
            }
            piano.showText(session.FormattedTrackName + ": " + score + "%", 50, false);

            if (save) // dont resave a loaded session
            {
                Debug.Log("Saving session - score = " + accuracy * 100);
                // Same but update accuracy
                var midiSessionDTO = new MidiSessionDto(RuntimeSettings.MIDI_FILE_NAME, accuracy, userEvents,
                                                        session.trackNoteDurations, session.noteScale, session.velocityIn, session.offsetStartTime);
                new MidiSessionController().putMidiSession(midiSessionDTO);
            }
        }