public ChatWindow()
        {
            InitializeComponent();
            DataContext = this;

            _voices = SynthesizerVoice.GetInstalledVoices();
            _outputDevices = OutputDevice.GetInstalledOutputDevices();

            _outputDevice = _outputDevices.First();
            _voice = new Voice(new WaveOut { DeviceNumber = _outputDevice.DeviceNumber });

            _voice.SelectVoice(_voices.First());
            VoiceComboBox.ItemsSource = _voices;
            VoiceComboBox.DisplayMemberPath = "Name";
            VoiceComboBox.SelectionChanged += VoiceComboBox_SelectionChanged;

            _voice.SelectOutput(_outputDevice);
            OutputComboBox.SelectedItem = _outputDevices;
            OutputComboBox.ItemsSource = _outputDevices;
            OutputComboBox.DisplayMemberPath = "Name";
            OutputComboBox.SelectionChanged += OutputComboBox_SelectionChanged;

            SendButton.Click += SendButton_Click;
            MessageTextBox.KeyUp += MessageTextBox_KeyUp;
        }
Example #2
0
        private static void PrintDescription(String propName, PropertyHolder prop, OutputDevice output)
        {
            if (prop.ShortDescription != null) {
                output.WriteBold("PROPERTY");
                output.WriteLine();
                output.WriteLine("\t" + propName + " : " + prop.ShortDescription);
                output.WriteLine();
            }

            String desc = prop.LongDescription;
            if (desc != null) {
                output.WriteBold("DESCRIPTION");
                output.WriteLine();
                output.WriteLine(desc);
            } else {
                output.WriteLine("no detailed help for '" + propName + "'");
            }
        }
Example #3
0
        public ReadingImproverKeyboardHandler(PitchPlease pitchPlease, int inputDeviceID)
        {
            this.pitchPlease = pitchPlease;

            if (InputDevice.DeviceCount == 0)
            {
                MessageBox.Show("No MIDI input devices available.");
            }
            else
            {
                try
                {
                    context  = SynchronizationContext.Current;
                    inDevice = new InputDevice(inputDeviceID);
                    inDevice.ChannelMessageReceived += HandleChannelMessageReceived;
                    inDevice.StartRecording();
                }
                catch (Exception ex)
                {
                    throw new ApplicationException("Error: " + ex);
                }
            }

            if (OutputDevice.DeviceCount == 0)
            {
                MessageBox.Show("No MIDI output devices available.");
            }
            else
            {
                try
                {
                    context   = SynchronizationContext.Current;
                    outDevice = new OutputDevice(0);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException("Error: " + ex);
                }
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            outDevice = new OutputDevice(0);

            stopwatch = new Stopwatch();
            stopwatch.Start();

            seq = new Sequence();
            seq.LoadCompleted += Seq_LoadCompleted;
            seq.Format         = 1;

            sequencer                       = new Sequencer();
            sequencer.Position              = 0;
            sequencer.Sequence              = seq;
            sequencer.ChannelMessagePlayed += Sequencer_ChannelMessagePlayed;
            sequencer.PlayingCompleted     += Sequencer_PlayingCompleted;
            sequencer.Stopped              += Sequencer_Stopped;
            sequencer.SysExMessagePlayed   += Sequencer_SysExMessagePlayed;
            sequencer.Chased               += Sequencer_Chased;

            writer = new SeqWriter();

            var currDirectory = Directory.GetCurrentDirectory();
            var midiDir       = Path.Combine(currDirectory, "MidiFiles");
            var files         = Directory.GetFiles(midiDir);

            Console.WriteLine("Reading files from " + midiDir + "...");
            foreach (string file in files)
            {
                Console.WriteLine("Sequencing file " + file + "...");
                //seq.Load(@"MidiFiles\The_Decisive_Battle_-_Final_Fantasy_VI.mid");
                seq.Load(file);

                SeqWriter.WriteSequenceToFiles(seq, Path.GetFileNameWithoutExtension(file));

                Console.WriteLine("Done.");
            }

            Console.WriteLine("Finished.");
        }
Example #5
0
        private void openFile(string path)
        {
            bool openOK = true;

            try
            {
                if (Path.GetDirectoryName(path).ToLower() == _repository.SourcesFolder.ToLower())
                {
                    _source = MetaSource.LoadFromFile(path, _repository);
                    _device = null;
                }
                else if (Path.GetDirectoryName(path).ToLower() == _repository.DevicesEmailFolder.ToLower())
                {
                    _source = null;
                    _device = OutputEmailDevice.LoadFromFile(path, false);
                }
                else if (Path.GetDirectoryName(path).ToLower() == _repository.DevicesFileServerFolder.ToLower())
                {
                    _source = null;
                    _device = OutputFileServerDevice.LoadFromFile(path, false);
                }
                else
                {
                    openOK = false;
                    MessageBox.Show("The configuration file must be in a repository folder.\r\nA sub-folder of " + _repository.RepositoryPath, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                openOK = false;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (openOK)
            {
                Properties.Settings.Default.LastUsedFile = path;
            }
            IsModified = false;
            init();
        }
Example #6
0
        static void Initialize()
        {
            inputDevice  = InputDevice.InstalledDevices[0];
            outputDevice = OutputDevice.InstalledDevices[1];

            inputDevice.Open();
            outputDevice.Open();

            for (int x = 0; x < 8; x++)
            {
                for (int y = 0; y < 8; y++)
                {
                    pitches[x, y] = (Pitch)((8 - y) * 10 + x + 1);
                }
            }

            for (int x = 0; x < 8; x++)
            {
                for (int y = 0; y < 8; y++)
                {
                    isNotePressed[pitches[x, y]] = false;
                }
            }

            inputDevice.NoteOn += NoteInput;

            analyzer a = new analyzer();

            a.readBar(@"D:\Test\Maps\map.txt");
            a = null;

            Clean();
            inputDevice.StartReceiving(null);
            isRendering = true;
            renderer.Start();

            stopwatch.Start();
            processor.Start();
        }
Example #7
0
        void NoteOff(OutputDevice outDevice, Note note)
        {
            float last = 0;

            // 악보에 있는 모든 음표를 재생합니다.
            KeyValuePair <float, int> p = note.ToMidi()[1];

            if (last != p.Key)
            {
                // 다음 Message의 타이밍이 올 때까지 쉽니다.
                // (만약 Unity에서 작업할 경우, Sleep 대신 Coroutine의 WaitForSecondsRealtime을 사용하면 됩니다.)
                System.Threading.Thread.Sleep((int)((p.Key - last) / 2 * 1000));
                last = p.Key;
            }

            if (p.Value <= 0)
            {
                // 음표의 재생을 멈춥니다.
                // (Midi message pair를 번역하여 Midi message를 생성합니다.)
                outDevice.Send(new ChannelMessage(ChannelCommand.NoteOff, -p.Value >> 16, -p.Value & 65535, 127));
            }
        }
Example #8
0
        /// <summary>
        /// 음표 하나를 음표의 길이와 관계없이 영원히 재생합니다.
        /// 이미 재생 중인 다른 음표와 동시에 재생할 수 있습니다.
        /// 재생을 멈추려면 해당 Staff에 Stop()을 호출해야 합니다.
        /// </summary>
        /// <param name="outDevice">출력 디바이스</param>
        /// <param name="note">재생할 음표</param>
        /// <param name="velocity">연주 세기 (0 ~ 127)</param>
        // (만약 Unity에서 작업할 경우, 타입을 void 대신 IEnumerator로 바꿔서 Coroutine으로 사용하세요.)
        public void PlayANoteForever(OutputDevice outDevice, Note note, int velocity = 127)
        {
            // 이미 재생 중인 악보이면 중복하여 재생하지 않습니다.
            if (isPlaying || velocity < 0 || velocity >= 128)
            {
                return;
            }
            isPlaying = true;
            //Console.WriteLine("Playing...");

            // 악보에 있는 모든 음표를 재생합니다.
            KeyValuePair <float, int> p = note.ToMidi()[0];

            if (p.Value > 0)
            {
                // 음표를 재생합니다.
                // (Midi message pair를 번역하여 Midi message를 생성합니다.)
                outDevice.Send(new ChannelMessage(ChannelCommand.NoteOn, p.Value >> 16, p.Value & 65535, velocity));
            }
            isPlaying = false;
            //Console.WriteLine("End of note.");
        }
Example #9
0
        /// <summary>
        /// 악보를 재생합니다.
        /// 이미 재생 중인 악보는 중복하여 재생할 수 없습니다.
        /// </summary>
        /// <param name="outDevice">출력 디바이스</param>
        // (만약 Unity에서 작업할 경우, 타입을 void 대신 IEnumerator로 바꿔서 Coroutine으로 사용하세요.)
        public void Play(OutputDevice outDevice)
        {
            // 이미 재생 중인 악보이면 중복하여 재생하지 않습니다.
            if (isPlaying)
            {
                return;
            }
            isPlaying = true;
            //Console.WriteLine("Playing...");

            float last = 0;

            // 악보에 있는 모든 음표를 재생합니다.
            foreach (KeyValuePair <float, int> p in ToMidi())
            {
                if (last != p.Key)
                {
                    // 다음 Message의 타이밍이 올 때까지 쉽니다.
                    // (만약 Unity에서 작업할 경우, Sleep 대신 Coroutine의 WaitForSecondsRealtime을 사용하면 됩니다.)
                    System.Threading.Thread.Sleep((int)((p.Key - last) / 2 * 1000));
                    last = p.Key;
                }

                if (p.Value > 0)
                {
                    // 음표를 재생합니다.
                    // (Midi message pair를 번역하여 Midi message를 생성합니다.)
                    outDevice.Send(new ChannelMessage(ChannelCommand.NoteOn, p.Value >> 16, p.Value & 65535, 127));
                }
                else
                {
                    // 음표의 재생을 멈춥니다.
                    // (Midi message pair를 번역하여 Midi message를 생성합니다.)
                    outDevice.Send(new ChannelMessage(ChannelCommand.NoteOff, -p.Value >> 16, -p.Value & 65535, 127));
                }
            }
            isPlaying = false;
            //Console.WriteLine("End of score.");
        }
    public LyrePlayerViewModel(IContainer ioc, MainWindowViewModel main)
    {
        _main        = main;
        _timeWatcher = PlaybackCurrentTimeWatcher.Instance;

        _events = ioc.Get <IEventAggregator>();
        _events.Subscribe(this);

        SelectedMidiInput = MidiInputs[0];

        _timeWatcher.CurrentTimeChanged += OnSongTick;

        // SystemMediaTransportControls is only supported on Windows 10 and later
        // https://docs.microsoft.com/en-us/uwp/api/windows.media.systemmediatransportcontrols
        if (Environment.OSVersion.Platform == PlatformID.Win32NT &&
            Environment.OSVersion.Version.Major >= 10)
        {
            _player = ioc.Get <MediaPlayer>();

            _player !.CommandManager.NextReceived     += (_, _) => Next();
            _player !.CommandManager.PreviousReceived += (_, _) => Previous();

            _player !.CommandManager.PlayReceived += async(_, _) => await PlayPause();

            _player !.CommandManager.PauseReceived += async(_, _) => await PlayPause();
        }

        try
        {
            _speakers = OutputDevice.GetByName("Microsoft GS Wavetable Synth");
        }
        catch (ArgumentException e)
        {
            new ErrorContentDialog(e, closeText: "Ignore").ShowAsync();

            SettingsView.CanUseSpeakers = false;
            Settings.UseSpeakers        = false;
        }
    }
Example #11
0
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!checkModified())
            {
                return;
            }

            _source = null;
            _device = null;

            object entityToSelect = null;

            if (sender == dataSourceToolStripMenuItem || sender == noSQLdataSourceToolStripMenuItem)
            {
                _source         = MetaSource.Create(_repository);
                _source.IsNoSQL = sender == noSQLdataSourceToolStripMenuItem;
                if (_source.IsNoSQL)
                {
                    //Add master table
                    MetaTable master = MetaTable.Create();
                    master.DynamicColumns = true;
                    master.IsEditable     = true;
                    master.Alias          = MetaData.MasterTableName;
                    master.Source         = _source;
                    _source.MetaData.Tables.Add(master);
                    entityToSelect = master;
                }
                else
                {
                    entityToSelect = _source.Connection;
                }
            }
            else if (sender == emailOutputDeviceToolStripMenuItem)
            {
                _device = OutputEmailDevice.Create();
            }
            IsModified = true;
            init(entityToSelect);
        }
Example #12
0
 // Switches output devices, turning off the old one (if any) and turning on the new one.
 private void UseOutputDevice(OutputDevice newOutputDevice)
 {
     if (newOutputDevice == outputDevice)
     {
         return;
     }
     if (clock.IsRunning)
     {
         clock.Stop();
         clock.Reset();
     }
     if (outputDevice != null)
     {
         if (outputDevice.IsOpen)
         {
             outputDevice.Close();
         }
     }
     outputDevice = newOutputDevice;
     outputDevice.Open();
     clock.Start();
 }
    // Use this for initialization
    void Start()
    {
        Debug.Log("init Stuff");
        GameObject go = GameObject.Find("SocketIO");

        socket = go.GetComponent <SocketIOComponent>();

        mainAudio = GetComponent <AudioSource>();

        // Debug.Log(OutputDevice.InstalledDevices.Count);
        // Launchpad Stuff
        if (OutputDevice.InstalledDevices.Count > 1)
        {
            outputDevice = OutputDevice.InstalledDevices[1];
            //Debug.Log(outputDevice.Name);
            if (outputDevice.IsOpen)
            {
                outputDevice.Close();
            }
            if (!outputDevice.IsOpen)
            {
                outputDevice.Open();
            }
            LightLaunchpad();
        }

        SocketIOListeners();

        //ConnectArduino();

        // InvokeRepeating("setEnergyBar", 1f, repeat_rate);
        curr_slave_bar = slaveEnergyBars[slave_index];

        // Initial Border Color for first Bar
        GameObject curr_slave_bg = curr_slave_bar.GetComponent <EnergyBarRiddle>().border;

        curr_slave_bg.GetComponent <Image>().color = Color.white;
        energyBar.transform.localScale             = new Vector3(this.transform.localScale.x, curr_energy, this.transform.localScale.z);
    }
Example #14
0
        // Called when the window loads.
        private void Form1_Load(object sender, EventArgs e)
        {
            // Set up a clock for scheduling output events.
            clock = new Clock(140);

            // Create persistent delegates which we can add and remove to events.
            noteOnHandler  = new InputDevice.NoteOnHandler(this.NoteOn);
            noteOffHandler = new InputDevice.NoteOffHandler(this.NoteOff);

            // Populate the list box with input devices, preferring the one from the previous
            // session if any.
            InputDevice preferredInputDevice =
                InputDevice.DeviceWithSpec(Properties.Settings.Default.MidiInputDeviceSpec);

            foreach (InputDevice device in InputDevice.InstalledDevices)
            {
                int idx = inputListBox.Items.Add(device.Spec);
                if (device == preferredInputDevice)
                {
                    UseInputDevice(device);
                    inputListBox.SelectedIndex = idx;
                }
            }

            // Populate the list box with output devices, preferring the one from the previous
            // session if any.
            OutputDevice preferredOutputDevice =
                OutputDevice.DeviceWithSpec(Properties.Settings.Default.MidiOutputDeviceSpec);

            foreach (OutputDevice device in OutputDevice.InstalledDevices)
            {
                int idx = outputListBox.Items.Add(device.Spec);
                if (device == preferredOutputDevice)
                {
                    UseOutputDevice(device);
                    outputListBox.SelectedIndex = idx;
                }
            }
        }
Example #15
0
        /// <summary>
        /// Function to connect with a LaunchpadDevice
        /// </summary>
        /// <param name="device">The Launchpad to connect to.</param>
        /// <returns>Returns bool if connection was successful.</returns>
        public bool connect(LaunchpadDevice device)
        {
            foreach (InputDevice id in Midi.InputDevice.InstalledDevices)
            {
                if (id.Name.ToLower() == device._midiName.ToLower())
                {
                    targetInput = id;
                    Console.WriteLine($"Connecting to : {id.Name}");
                    targetInput.Open();
                    if (id.Name == "Launchpad MK2")
                    {
                        Console.WriteLine($"Detected as MK2, using updated button positions");
                        rowBasePitch  = rowBasePitch_launchpadmk2;
                        ccBaseControl = ccBaseControl_launchpadmk2;
                        launchpadType = LaunchpadType.MK2;
                    }
                    else
                    {
                        rowBasePitch  = rowBasePitch_launchpadMini; // works-ish with a lot of them
                        ccBaseControl = ccBaseControl_launchpadMini;
                        launchpadType = LaunchpadType.Mini;
                    }
                    Console.WriteLine($"isReceiving: {targetInput.IsReceiving}, open: {targetInput.IsOpen}");
                    targetInput.NoteOn        += new InputDevice.NoteOnHandler(midiPress);
                    targetInput.ControlChange += new InputDevice.ControlChangeHandler(midiCC);
                    targetInput.StartReceiving(null);
                }
            }
            foreach (OutputDevice od in Midi.OutputDevice.InstalledDevices)
            {
                if (od.Name.ToLower() == device._midiName.ToLower())
                {
                    targetOutput = od;
                    od.Open();
                }
            }

            return(true); // targetInput.IsOpen && targetOutput.IsOpen;
        }
Example #16
0
        public bool bind(Dictionary <String, LogicalOutputDevice> logicalOutputDeviceDict)
        {
            cc7Scale = ((double)cc7Max - (double)cc7Min) / (double)127;     // The portion of 127 of the actual output range

            if (logicalOutputDeviceDict.ContainsKey(deviceName))
            {
                this.device = logicalOutputDeviceDict[deviceName].device;

                foreach (String key in soundGeneratorPatchDict.Keys)
                {
                    SoundGeneratorPatch patch = soundGeneratorPatchDict[key];
                    patch.bind(this);
                }

                return(true);
            }
            else
            {
                this.device = null;
                return(false);
            }
        }
Example #17
0
    public void ledOnRed(int x, int y)
    {
        if (x < 0 || x > 8 || y < 0 || y > 7)
        {
            //Debug.Log(new System.ArgumentException("Button out of bounds"));
            return;
        }

        try
        {
            if (launchpadOutput != null)
            {
                launchpadOutput.SendNoteOn(Channel.Channel1, (Pitch)(x + 16 * (7 - y)), 15);
            }
        }
        catch (DeviceException)
        {
            ready           = false;
            launchpadOutput = null;
            launchpadInput  = null;
        }
    }
Example #18
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            InstrumentoPreview.Image = GetImageResource("Cover");

            MidiLoaded       = false;
            InstrumentLoaded = false;
            playing          = false;

            //Preenche Combobox de transposição
            for (int i = -24; i <= 24; i++)
            {
                TransSemitones.Items.Add(String.Concat(i.ToString(), " semitons"));
            }
            TransSemitones.SelectedIndex = 24;


            //Carregando Dispositivos MIDI
            if (OutputDevice.DeviceCount > 0)
            {
                try
                {
                    List <string> devices = new List <string>();
                    for (int i = 0; i < OutputDevice.DeviceCount; i++)
                    {
                        devices.Add(OutputDevice.GetDeviceCapabilities(i).name);
                    }

                    DeviceSelect.Items.AddRange(devices.ToArray());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error !", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            else
            {
                MessageBox.Show("Não foram encontrados dispositivos de saída neste computador. \n Não será possível reproduzir sons...", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Example #19
0
        /// <inheritdoc />
        public void Dump(IPatch patch, int deviceId)
        {
            var digitalPatch = (Patch)patch;

            using (var output = new OutputDevice(deviceId))
            {
                _logger.DataDump("Dumping Patch.Common");
                output.Send(SysExUtils.GetMessage(CommonAddressOffset, digitalPatch.Common.GetBytes()));

                _logger.DataDump("Dumping Patch.PartialOne");
                output.Send(SysExUtils.GetMessage(PartialAddressOffset(DigitalPartial.First), digitalPatch.PartialOne.GetBytes()));

                _logger.DataDump("Dumping Patch.PartialTwo");
                output.Send(SysExUtils.GetMessage(PartialAddressOffset(DigitalPartial.Second), digitalPatch.PartialTwo.GetBytes()));

                _logger.DataDump("Dumping Patch.PartialThree");
                output.Send(SysExUtils.GetMessage(PartialAddressOffset(DigitalPartial.Third), digitalPatch.PartialThree.GetBytes()));

                _logger.DataDump("Dumping Patch.Modifiers");
                output.Send(SysExUtils.GetMessage(ModifiersAddressOffset, digitalPatch.Modifiers.GetBytes()));
            }
        }
Example #20
0
        void PlayChordRun(OutputDevice outputDevice, Chord chord, int millisecondsBetween)
        {
            Pitch previousNote = (Pitch)(-1);

            for (Pitch pitch = Pitch.A0; pitch < Pitch.C8; ++pitch)
            {
                if (chord.Contains(pitch))
                {
                    if (previousNote != (Pitch)(-1))
                    {
                        outputDevice.SendNoteOff(Channel.Channel1, previousNote, 80);
                    }
                    outputDevice.SendNoteOn(Channel.Channel1, pitch, 80);
                    Thread.Sleep(millisecondsBetween);
                    previousNote = pitch;
                }
            }
            if (previousNote != (Pitch)(-1))
            {
                outputDevice.SendNoteOff(Channel.Channel1, previousNote, 80);
            }
        }
Example #21
0
        private void InitOrRefreshDevicesList()
        {
            this.SuspendLayout();

            if (InputDevice.GetDevicesCount() != nbInputDevices)
            {
                nbInputDevices = InputDevice.GetDevicesCount();
                InputDevicesComboBox.Items.Clear();
                InputDevicesComboBox.Items.Add("Choose midi input source");
                InputDevicesComboBox.Items.Add("Midi events from network");
                InputDevice.GetAll().ToList().ForEach(inputDevice => InputDevicesComboBox.Items.Add(inputDevice.Name));
                if (inputDeviceName != null && InputDevicesComboBox.Items.Contains(inputDeviceName))
                {
                    InputDevicesComboBox.SelectedItem = inputDeviceName;
                }
                else
                {
                    InputDevicesComboBox.SelectedIndex = 0;
                }
            }

            if (OutputDevice.GetDevicesCount() != nbOutputDevices)
            {
                nbOutputDevices = OutputDevice.GetDevicesCount();
                OutputDevicesComboBox.Items.Clear();
                OutputDevicesComboBox.Items.Add("Choose midi output destination");
                OutputDevicesComboBox.Items.Add("Midi events to network");
                OutputDevice.GetAll().ToList().ForEach(outputDevice => OutputDevicesComboBox.Items.Add(outputDevice.Name));
                if (outputDeviceName != null && OutputDevicesComboBox.Items.Contains(outputDeviceName))
                {
                    OutputDevicesComboBox.SelectedItem = outputDeviceName;
                }
                else
                {
                    OutputDevicesComboBox.SelectedIndex = 0;
                }
            }
            this.ResumeLayout();
        }
Example #22
0
        public void AddRoute(int inport, int outport)
        {
            if (!outMidiList.Contains(outport))
            {
                outMidiList.Add(outport);
                om[outport].InitOutputDevice();
            }

            if (inport > MINMIDIPORT)
            {
                MidiOutCaps caps = OutputDevice.GetDeviceCapabilities(outport);

                umpl.Add(inport, om[outport]);
            }
            else
            {
                if (!inMidiList.Contains(inport))
                {
                    inMidiList.Add(inport);
                    im[inport].InitInputDevice();
                    //if (MidiRoutes[i].AllRoutes)
                    {
                        im[inport].inMIDI.SysCommonMessageReceived   += HandleSysCommonMessageReceived;
                        im[inport].inMIDI.ChannelMessageReceived     += HandleChannelMessageReceived;
                        im[inport].inMIDI.SysExMessageReceived       += HandleSysExMessageReceived;
                        im[inport].inMIDI.SysRealtimeMessageReceived += HandleSysRealtimeMessageReceived;
                        im[inport].inMIDI.Error += new EventHandler <Sanford.Multimedia.ErrorEventArgs>(inDevice_Error);
                    }
                }

                if (MidiRoutes[inport] == null)
                {
                    MidiRoutes[inport] = new Route();
                }
                MidiRoutes[inport].AddRoute(outport, true);
            }

            dirty = true;
        }
Example #23
0
 public MidiControllerToolkit()
 {
     #region ToolkitThings
     if (OutputDevice.DeviceCount == 0)
     {
         MessageBox.Show("No MIDI output devices available.", "Error!",
                         MessageBoxButtons.OK, MessageBoxIcon.Stop);
     }
     else
     {
         try
         {
             outDevice = new OutputDevice(outDeviceID);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message, "Error!",
                             MessageBoxButtons.OK, MessageBoxIcon.Stop);
         }
     }
     #endregion
 }
Example #24
0
        public void RefreshDevices()
        {
            int Count = 0, i = 0, j = 0;

            List <Device> devList = new List <Device>();

            Count = InputDevice.DeviceCount;
            for (i = 0; i < Count; i++)
            {
                devList.Add(new Device(i));
            }

            Count = OutputDevice.DeviceCount;
            for (i = 0; i < Count; i++)
            {
                MidiOutCaps cap = OutputDevice.GetDeviceCapabilities(i);
                for (j = 0; j < devList.Count; j++)
                {
                    if (devList[j].Name == cap.name)
                    {
                        devList[j].SetOutputDevice(i);
                    }
                }
            }

            /*foreach (Device dev in devList)
             * {
             *  bool found = true;
             *
             *  for(int i =0; i<mDeviceList.Count; i++)
             *      if (mDeviceList[i].Name == dev.Name)
             *      {
             *          found = true;
             *          break;
             *      }
             *  if(!found)
             * }*/
            mDeviceList = devList;
        }
Example #25
0
        public Launchpad(InputDevice inputDevice, OutputDevice outputDevice, Clock clock)
        {
            this.inputDevice  = inputDevice;
            this.outputDevice = outputDevice;
            this.clock        = clock;
            if (this.inputDevice.IsOpen)
            {
                this.inputDevice.Close();
            }
            if (this.outputDevice.IsOpen)
            {
                this.outputDevice.Close();
            }

            this.inputDevice.Open();
            this.inputDevice.NoteOn += new InputDevice.NoteOnHandler(NoteOn);
            this.inputDevice.StartReceiving(null);

            this.outputDevice.Open();
            this.ShowColours();
            DemoSetup();
        }
Example #26
0
        public void Shift(OutputDevice outputDevice)
        {
            if (Sequence == null || Sequence.Count == 0 || status == LayerStatus.Finished)
            {
                return;
            }
            if (status == LayerStatus.NotStarted)
            {
                status = LayerStatus.Playing;
                StartNote(pos, outputDevice);
                length = 1;
                return;
            }

            var note = Sequence[pos];

            if (length < note.Length)
            {
                length++;
                return;
            }

            StopNote(pos, outputDevice);
            pos++;
            if (pos == Sequence.Count)
            {
                if (!loop)
                {
                    status = LayerStatus.Finished;
                    return;
                }

                pos = 0;
            }

            StartNote(pos, outputDevice);
            length = 1;
        }
Example #27
0
        protected override void DoFeedBack(TodoVariable var, TodoMidiInput source)
        {
            for (int i = 0; i < this.outputstatus.Count; i++)
            {
                if (this.outputstatus[i] == eTodoMidiStatus.Started)
                {
                    try
                    {
                        OutputDevice   dev = this.outdevs[i];
                        ChannelCommand cmd = ChannelCommand.Controller;
                        if (source.ControlType == eTodoMidiType.Controller)
                        {
                            cmd = ChannelCommand.Controller;
                        }
                        else
                        {
                            if (source.ControlType == eTodoMidiType.Note)
                            {
                                if (var.ValueRaw == 0.0)
                                {
                                    cmd = ChannelCommand.NoteOff;
                                }
                                else
                                {
                                    cmd = ChannelCommand.NoteOn;
                                }
                            }
                        }

                        ChannelMessage msg = new ChannelMessage(cmd, source.MidiChannel, source.ControlValue, Convert.ToInt32(var.ValueRaw * 127.0));
                        dev.Send(msg);
                    }
                    catch
                    {
                    }
                }
            }
        }
Example #28
0
        public static void Start()
        {
            Log.WriteLine("PAW-01 Signal Converter Host, v0.1");
            stopped = false;

            Log.WriteLine("Opening controller port...");
            controllerPort             = new SerialPort("COM127", 1000000);
            controllerPort.ReadTimeout = 1000;
            controllerPort.Open();
            Log.WriteLine("Opening keyboard port...");
            keyboardPort             = new SerialPort("COM255", 250000);
            keyboardPort.ReadTimeout = 1000;
            keyboardPort.Open();
            Log.WriteLine("Opening Midi output port...");
            midiout = new OutputDevice(1);
            Log.WriteLine("Opening Midi input port...");
            midiin = new InputDevice(1);
            midiin.ChannelMessageReceived += (o, e) => MidiInHandler(e.Message);
            midiin.StartRecording();
            Log.WriteLine("Opening input simulator...");
            simulator = new InputSimulator();

            Log.WriteLine("Initializing mouse...");
            mouseProc = new Thread(MouseProc);
            mouseProc.Start(null);

            Log.WriteLine("Initializing keyboard...");
            keyboardPort.DataReceived += KeyboardInHandler;

            Log.WriteLine("Initializing controller...");
            controllerPort.DataReceived += ControllerInHandler;

            Log.WriteLine("Initializing stats monitor...");
            statsProc = new Thread(StatsProc);
            statsProc.Start();

            Log.WriteLine("PAW-01 Host started.");
        }
Example #29
0
        private static void PrintDescription(String propName, PropertyHolder prop, OutputDevice output)
        {
            if (prop.ShortDescription != null)
            {
                output.WriteBold("PROPERTY");
                output.WriteLine();
                output.WriteLine("\t" + propName + " : " + prop.ShortDescription);
                output.WriteLine();
            }

            String desc = prop.LongDescription;

            if (desc != null)
            {
                output.WriteBold("DESCRIPTION");
                output.WriteLine();
                output.WriteLine(desc);
            }
            else
            {
                output.WriteLine("no detailed help for '" + propName + "'");
            }
        }
Example #30
0
        public static void PlayRunUpKeyboard(OutputDevice outputDevice, Predicate <Note> predicate,
                                             int millisecondsBetween)
        {
            Note previousNote = (Note)(-1);

            for (Note note = Note.A0; note < Note.C8; ++note)
            {
                if (predicate(note))
                {
                    if (previousNote != (Note)(-1))
                    {
                        outputDevice.SendNoteOff(Channel.Channel1, previousNote, 80);
                    }
                    outputDevice.SendNoteOn(Channel.Channel1, note, 80);
                    Thread.Sleep(millisecondsBetween);
                    previousNote = note;
                }
            }
            if (previousNote != (Note)(-1))
            {
                outputDevice.SendNoteOff(Channel.Channel1, previousNote, 80);
            }
        }
Example #31
0
        public Instrument(int numOfNotes, bool holdNote = false)
        {
            noteIndexLeft  = -1;
            noteIndexRight = -1;

            for (int i = 0; i < isNotePlayingArray.Length / 2; i++)
            {
                isNotePlayingArray[0, i] = false;
                isNotePlayingArray[1, i] = false;
            }

            this.holdNote   = holdNote;
            this.numOfNotes = numOfNotes;
            this.scale      = GetScale(numOfNotes);

            outputDevice = OutputDevice.InstalledDevices.Single(d => d.Name == "loopMIDIport1");

            this.outputDevice.Open();
            if (!outputDevice.IsOpen)
            {
                throw new InvalidOperationException();
            }
        }
Example #32
0
        private void Note(bool on, int note, ChannelMessageBuilder builder, OutputDevice output)
        {
            if (on)
            {
                builder.Command     = ChannelCommand.NoteOn;
                builder.MidiChannel = 0;
                builder.Data1       = note + 45;
                builder.Data2       = 127;
                builder.Build();

                output.Send(builder.Result);
            }
            else
            {
                builder.Command     = ChannelCommand.NoteOff;
                builder.MidiChannel = 0;
                builder.Data1       = note + 45;
                builder.Data2       = 0;
                builder.Build();

                output.Send(builder.Result);
            }
        }
Example #33
0
        public static string Output(this FPdf document, string name, OutputDevice destination)
        {
            // Output PDF to some destination
            if (document.State < 3)
            {
                document.Close();
            }
            if (destination == OutputDevice.Default)
            {
                if (string.IsNullOrEmpty(name))
                {
                    name = "doc.pdf";
                    destination = OutputDevice.StandardOutput;
                }
                else
                {
                    destination = OutputDevice.SaveToFile;
                }
            }
            switch (destination)
            {
                case OutputDevice.StandardOutput:
                    HttpContext.Current.Response.AppendHeader("Content-Type: application/pdf", "");
                    HttpContext.Current.Response.AppendHeader("Content-Disposition: inline; filename=\"" + name + "\"",
                                                              "");
                    HttpContext.Current.Response.AppendHeader("Cache-Control: private, max-age=0, must-revalidate", "");
                    HttpContext.Current.Response.AppendHeader("Pragma: public", "");
                    HttpContext.Current.Response.Write(document.Buffer);
                    break;

                case OutputDevice.Download:
                    // Download file
                    HttpContext.Current.Response.AppendHeader("Content-Type: application/x-download", "");
                    HttpContext.Current.Response.AppendHeader(
                        "Content-Disposition: attachment; filename=\"" + name + "\"", "");
                    HttpContext.Current.Response.AppendHeader("Cache-Control: private, max-age=0, must-revalidate", "");
                    HttpContext.Current.Response.AppendHeader("Pragma: public", "");
                    HttpContext.Current.Response.Write(document.Buffer);
                    break;

                case OutputDevice.SaveToFile:
                    // Save to local file
                    FileStream f = FileSystemSupport.FileOpen(name, "wb");
                    if (!TypeSupport.ToBoolean(f))
                    {
                        throw new InvalidOperationException( "Unable to create output file: " + name);
                    }
                    var writer = new StreamWriter(f, FPdf.PrivateEncoding);
                    writer.Write(document.Buffer);
                    writer.Close();
                    break;

                case OutputDevice.ReturnAsString:
                    return document.Buffer;

                default:
                    throw new InvalidOperationException("Incorrect output destination: " + destination);
                    break;
            }
            return string.Empty;
        }
Example #34
0
 private static OutputDevice OpenStackedDevice(Stack<OutputDevice> stack, OutputDevice newOut)
 {
     OutputDevice origOut = stack.Peek();
     OutputDevice outDevice = new StackedDevice(origOut, newOut);
     stack.Push(outDevice);
     return outDevice;
 }
Example #35
0
 public StackedWriter(OutputDevice a, OutputDevice b)
 {
     this.a = a;
     this.b = b;
 }
Example #36
0
        /// <summary>
        /// Returns the file extension for the specified output device
        /// </summary>
        /// <param name="outputDevice"></param>
        /// <returns></returns>
        public static string GetOutputDeviceFileExtension(OutputDevice outputDevice)
        {
            switch (outputDevice)
            {
                case OutputDevice.png16m:
                case OutputDevice.pnggray:
                case OutputDevice.png256:
                case OutputDevice.png16:
                case OutputDevice.pngmono:
                case OutputDevice.pngalpha:
                    {
                        return "png";
                    }
                case OutputDevice.jpeg:
                case OutputDevice.jpeggray:
                    {
                        return "jpg";
                    }
                case OutputDevice.pbm:
                case OutputDevice.pbmraw:
                case OutputDevice.pgm:
                case OutputDevice.pgmraw:
                case OutputDevice.pgnm:
                case OutputDevice.pgnmraw:
                case OutputDevice.pnm:
                case OutputDevice.pnmraw:
                case OutputDevice.ppm:
                case OutputDevice.ppmraw:
                case OutputDevice.pkm:
                case OutputDevice.pkmraw:
                case OutputDevice.pksm:
                case OutputDevice.pksmraw:
                    {
                        return "pnm";
                    }
                case OutputDevice.tiffgray:
                case OutputDevice.tiff12nc:
                case OutputDevice.tiff24nc:
                case OutputDevice.tiff32nc:
                case OutputDevice.tiffsep:
                case OutputDevice.tiffcrle:
                case OutputDevice.tiffg3:
                case OutputDevice.tiffg32d:
                case OutputDevice.tiffg4:
                case OutputDevice.tifflzw:
                case OutputDevice.tiffpack:
                    {
                        return "tif";
                    }
                case OutputDevice.faxg3:
                case OutputDevice.faxg32d:
                case OutputDevice.faxg4:
                    {
                        return "raw";
                    }
                case OutputDevice.bmpgray:
                case OutputDevice.bmpsep1:
                case OutputDevice.bmpsep8:
                case OutputDevice.bmp16:
                case OutputDevice.bmp256:
                case OutputDevice.bmp16m:
                case OutputDevice.bmp32b:
                    {
                        return "bmp";
                    }
                case OutputDevice.pcxmono:
                case OutputDevice.pcxgray:
                case OutputDevice.pcx16:
                case OutputDevice.pcx256:
                case OutputDevice.pcx24b:
                case OutputDevice.pcxcmyk:
                    {
                        return "pcx";
                    }
                case OutputDevice.psdcmyk:
                case OutputDevice.psdrgb:
                    {
                        return "psd";
                    }
                case OutputDevice.pdfwrite:
                    {
                        return "pdf";
                    }
                case OutputDevice.pswrite:
                    {
                        return "ps";
                    }
                case OutputDevice.epswrite:
                    {
                        return "eps";
                    }
                case OutputDevice.pxlmono:
                case OutputDevice.pxlcolor:
                    {
                        return "pxl";
                    }

                default: return String.Empty;
            }
        }
Example #37
0
 /// <summary>
 /// Returns the Output Device parameter
 /// </summary>
 /// <param name="outputDevice"></param>
 /// <returns></returns>
 public static string GetOutputDeviceParameter(OutputDevice outputDevice)
 {
     if (Enum.IsDefined(typeof(OutputDevice), outputDevice))
     {
         return String.Concat("-sDEVICE=", outputDevice);
     }
     else
     {
         return "-sDEVICE=unknown";
     }
 }
Example #38
0
        public List<string> Convert(OutputDevice outputDevice, DeviceOption[] deviceOptions, string inputFileName, string outputPath, string outputFileName, string temporaryFileFolder, int resolution)
        {
            System.Diagnostics.Debug.WriteLine("GhostScript Convert called, inputFileName=" + inputFileName + " temporaryFileFolder=" + temporaryFileFolder);

            InitializePrivateMembers();

            List<string> outputFilenames = new List<string>();

            // Check if input file is supported
            if (!FileTypeSupported(Path.GetExtension(inputFileName)))
            {
                throw (new GhostScriptException((int)ReturnCode.FileTypeNotSupportedByInterpreter, GhostScript.GetGSErrorMessage((int)ReturnCode.FileTypeNotSupportedByInterpreter)));
            }

            // Construct Ouput Filename Template
            string outputFilenameTemplate = Path.Combine(outputPath, outputFileName);

            if (outputFileName.Trim() == String.Empty)
            {
                // Construct output filename template for multipage document
                string filename = Path.GetFileNameWithoutExtension(inputFileName.Replace("%", "_"));
                //filename = String.Concat(filename,  (filename.EndsWith("_") ? String.Empty : "_"));
                outputFilenameTemplate = Path.Combine(outputPath, String.Concat(filename, "%01d.", GetOutputDeviceFileExtension(outputDevice)));
            }

            // Copy source file and perform processing on the copy
            string temporaryInputFilename = Path.Combine(temporaryFileFolder, String.Concat(Guid.NewGuid().ToString("N"), Path.GetExtension(inputFileName)));

            System.IO.File.Copy(inputFileName, temporaryInputFilename, true);

            // Construct Command Parameters to pass to the GhostScript DLL
            List<string> commandList = new List<string>();
            commandList.Add("convert"); //First parameter is ignored
            commandList.Add("-dSAFER");
            commandList.Add("-dBATCH");
            commandList.Add("-dNOPAUSE");
            commandList.Add("-dCOLORSCREEN");
            commandList.Add("-dDOINTERPOLATE");
            commandList.Add("-dTextAlphaBits=4");
            commandList.Add("-dGraphicsAlphaBits=4");
            commandList.Add("-dUseCIEColor");

            // Specify Output Device
            commandList.Add(GetOutputDeviceParameter(outputDevice));

            // Specify Output Device Options
            commandList.AddRange(GetDeviceOptionParameters(deviceOptions));

            // Specify Resolution
            if (resolution > 0)
            {
                commandList.Add(GetResolutionParameter(resolution));
            }

            // other parameters
            //commandList.Add("-c3000000");
            //commandList.Add("setvmthreshold -f");
            //commandList.Add("-r600");                 // Sets DPI resolution where XRES = YRES
            //commandList.Add("-r300x400");             // Sets DPI resolution (-rXRESxYRES) where XRES and YRES are defferent

            // Specify Output File
            commandList.Add(String.Concat("-sOutputFile=", outputFilenameTemplate));

            // Specify Input File
            commandList.Add(temporaryInputFilename);

            // Convert the command list into a string array
            string[] commandParameters = new string[commandList.Count];
            for (int counter = 0; counter <= commandList.Count - 1; counter++)
            {
                commandParameters[counter] = commandList[counter];
            }

            try
            {
                System.Diagnostics.Debug.WriteLine("GhostScript Convert.CallGSDLL");
                // Call GhostScript DLL
                CallGSDll(commandParameters);

                // Construct the result, listing output files in the output folder in the correct order
                string outputFile = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(outputFilenameTemplate.Replace("%01d", String.Empty)));
                string outputFileExtension = Path.GetExtension(outputFilenameTemplate);
                int counter = 1;
                string outputFileNameCheck = String.Concat(outputFile, counter, outputFileExtension);
                while (System.IO.File.Exists(outputFileNameCheck))
                {
                    // Add ouput file name to result
                    outputFilenames.Add(outputFileNameCheck);

                    // Increment counter, we use this number to check for the next file
                    counter++;

                    // Construct next filename to check
                    outputFileNameCheck = String.Concat(outputFile, counter, outputFileExtension);
                }

                RaiseProcessingCompletedEvent(new ProcessingCompletedEventArgs(_PageCount, outputFilenames));
            }
            finally
            {
                // Delete Temporary Input File
                if (System.IO.File.Exists(temporaryInputFilename))
                {
                    try
                    {
                        System.IO.File.Delete(temporaryInputFilename);
                    }
                    catch
                    {
                        // Ignore error the temporary file cannot be deleted
                    }
                }
            }

            System.Diagnostics.Debug.WriteLine("GhostScript Convert outputFileNameCount = " + outputFilenames.Count.ToString());

            return outputFilenames;
        }
		public DeviceInfo GetDevice (OutputDevice n)
		{
			if (n != OutputDevice.AUTO)
				return null;
			
			DeviceInfo d = devices.Values.OrderByDescending (dev => dev.TotalBytes).FirstOrDefault ();
			foreach (DeviceInfo device in devices.Values)
				if (d == null || device.TotalRate > d.TotalRate)
					d = device;
			
			return d;
		}
Example #40
0
            public StackedDevice(OutputDevice a, OutputDevice b)
            {
                _a = a;
                _b = b;

                writer = new StackedWriter(a, b);
            }