Cross Platform Application to allow control with a MIDI controller
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
3.6 KiB

// Author: Gockner, Simon
// Created: 2021-04-07
// Copyright(c) 2021 SimonG. All Rights Reserved.
using System.Collections.Generic;
using System.Linq;
using Lib.Audio.Controls.Buttons.Factories;
using Lib.Audio.Controls.Buttons.Interfaces;
using Lib.Audio.Controls.Factories;
using Lib.Audio.Controls.Interfaces;
using Lib.Audio.Interfaces;
using Lib.Driver.Xml;
using Lib.Midi.Interfaces;
using Lib.Midi.Messages;
using Lib.Midi.Messages.Interfaces;
namespace Lib.Audio
{
public class Channel : IChannel
{
private readonly int _channelNumber;
private IMidiMessage? _acknowledgeMessage;
public Channel(XmlChannel xmlChannel,
IFaderFactory faderFactory,
IKnobFactory knobFactory,
IButtonFactory buttonFactory)
{
_channelNumber = xmlChannel.ChannelNumber;
if (xmlChannel.Fader != null)
{
Fader = faderFactory.Create(xmlChannel.Fader);
Fader.PositionChanged += OnFaderPositionChanged;
}
if (xmlChannel.Knob != null)
Knob = knobFactory.Create();
if (xmlChannel.Buttons != null)
{
Buttons = new List<IButton>();
foreach (var button in xmlChannel.Buttons)
Buttons.Add(buttonFactory.Create(button, _channelNumber));
}
}
public IFader? Fader { get; }
public IKnob? Knob { get; }
public List<IButton>? Buttons { get; }
public IControllable? Controllable { get; private set; }
public void MapControllable(IControllable controllable) => Controllable = controllable;
public void HandleMessage(IMidiMessage message)
{
if (message is NoteOnMessage noteOnMessage)
{
if (Fader?.NoteNumber == noteOnMessage.NoteNumber)
Fader.IsTouched = true;
else
{
IButton? button = Buttons?.FirstOrDefault(b => b.NoteNumber == noteOnMessage.NoteNumber);
_acknowledgeMessage = button?.HandleOn(Controllable, noteOnMessage.Velocity);
}
}
else if (message is NoteMessage noteMessage)
{
if (Fader?.NoteNumber == noteMessage.NoteNumber)
{
Fader.IsTouched = false;
_acknowledgeMessage = new PitchWheelChangeMessage(0, _channelNumber, Fader.Position);
}
else
{
IButton? button = Buttons?.FirstOrDefault(b => b.NoteNumber == noteMessage.NoteNumber);
_acknowledgeMessage = button?.HandleOff(Controllable, noteMessage.Velocity);
}
}
else if (message is PitchWheelChangeMessage pitchWheelChangeMessage)
{
if (Fader != null)
Fader.Position = pitchWheelChangeMessage.Pitch;
}
}
public void SendAcknowledge(IMidiCommunication midiCommunication)
{
if (_acknowledgeMessage == null)
return;
midiCommunication.Send(_acknowledgeMessage);
_acknowledgeMessage = null;
}
private void OnFaderPositionChanged(object? sender, int position)
{
if (sender is not IFader fader)
return;
Controllable?.SetVolume(fader.RelativePosition);
}
public override string ToString() => $"Channel {_channelNumber}";
}
}