Click here to Skip to main content
15,885,365 members
Articles / Multimedia / DirectX

C# Synth Toolkit - Part I

Rate me:
Please Sign up or sign in to vote.
4.89/5 (33 votes)
17 Aug 2007MIT13 min read 238K   6.4K   130  
A toolkit for creating software synthesizers with C# and Managed DirectX.
#region License

/* Copyright (c) 2007 Leslie Sanford
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to 
 * deal in the Software without restriction, including without limitation the 
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 
 * sell copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software. 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 * THE SOFTWARE.
 */

#endregion

#region Contact

/*
 * Leslie Sanford
 * Email: jabberdabber@hotmail.com
 */

#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Sanford.Multimedia.Synth;

namespace SimpleSynthDemo
{
    /// <summary>
    /// Represents a "naive" oscillator capable of producing basic waveforms.
    /// </summary>
    public class SimpleOscillator : StereoSynthComponent, IProgrammable, IBendable
    {
        #region SimpleOscillator Members

        #region Enumerations

        /// <summary>
        /// Constants representing the SimpleOscillator's parameters.
        /// </summary>
        public enum ParameterId
        {
            Panning,
            WaveformType
        }

        /// <summary>
        /// Constants representing the types of waveforms the 
        /// SimpleOscillator can produce.
        /// </summary>
        public enum WaveformType
        {
            Sawtooth,
            Square,
            Triangle
        }        

        #endregion

        #region Fields

        #region Constants

        /// <summary>
        /// The number of waveforms.
        /// </summary>
        public const int WaveformTypeCount = (int)WaveformType.Triangle + 1;

        #endregion

        // Determines the oscillator's position in the stereo field.
        private float panning = 0.5f;

        // The type of waveform the SimpleOscillator is currently producing.
        private WaveformType waveType = WaveformType.Sawtooth;

        // The note that is currently playing.
        private int currentNote;

        // Phase accumulator.
        private float accumulator = 0;

        // The amount to modulate the pitch based on pitch wheel movement.
        private float pitchBendModulation = 0;

        // Indicates whether the SimpleOscillator is currently playing.
        private bool playing = false;

        // Indicates whether the SimpleOscillator will overwrite the 
        // values in its buffer each time it synthesizes output.
        private bool synthesizeReplaceEnabled = true;

        #endregion

        #region Constructors

        public SimpleOscillator(SampleRate sampleRate, StereoBuffer buffer) : base(sampleRate, buffer)
        {
            Initialize();
        }

        public SimpleOscillator(SampleRate sampleRate, StereoBuffer buffer, string name) : base(sampleRate, buffer, name)
        {
            Initialize();
        }

        private void Initialize()
        {
            currentNote = A440NoteNumber;
        }

        #endregion       
 
        #region Methods
        
        public override void Synthesize(int offset, int count)
        {
            // Get StereoBuffer; we'll write the synthesized output to 
            // this buffer.
            float[,] buffer = GetBuffer();

            Debug.Assert(buffer != null);
            Debug.Assert(buffer.GetLength(1) >= offset + count);

            // Synthesized output.
            float output = 0;

            // Modulate the current pitch with pitch bend modulation value. 
            float modNote = currentNote + NotesPerOctave * pitchBendModulation;           

            // If the current pitch was modulated to a negative value 
            // (out of range).
            if(modNote < 0)
            {
                // Clip modulated pitch.
                modNote = 0;
            }
            // Else the current pitch was modulated to a positive value 
            // that is out of range.
            else if(modNote > NoteCount - 1)
            {
                // Clip modulated pitch.
                modNote = NoteCount - 1;
            }

            // Calculate the phase increment value.
            float increment = PowerOfTwoTable.GetPower((modNote - A440NoteNumber) / NotesPerOctave) * A440Frequency / SamplesPerSecond;

            // The end point in the buffer where we stop synthesizing.
            int endIndex = offset + count;

            for(int i = offset; i < endIndex; i++)
            {
                switch(waveType)
                {
                    case WaveformType.Sawtooth:
                        output = 1 - 2 * accumulator;
                        break;

                    case WaveformType.Square:
                        if(accumulator < 0.5)
                        {
                            output = -1;
                        }
                        else
                        {
                            output = 1;
                        }
                        break;

                    case WaveformType.Triangle:
                        if(accumulator < 0.5)
                        {
                            output = 1 - 4 * accumulator;
                        }
                        else
                        {
                            output = 1 - 4 * (1 - accumulator);
                        }
                        break;

                    default:
                        Debug.Fail("Unhandled waveform type.");
                        break;
                }

                if(synthesizeReplaceEnabled)
                {
                    buffer[0, i] = output * (1 - panning);
                    buffer[1, i] = output * panning;
                }
                else
                {
                    buffer[0, i] += output * (1 - panning);
                    buffer[1, i] += output * panning;
                }

                accumulator += increment;

                if(accumulator >= 1)
                {
                    accumulator -= 1;
                }
            }
        }

        public override void Trigger(int previousNote, int note, float velocity)
        {
            currentNote = note;

            playing = true;
        }

        public override void Release(float velocity)
        {
            playing = false;
        }

        #endregion

        #region Properties

        public override bool SynthesizeReplaceEnabled
        {
            get
            {
                return synthesizeReplaceEnabled;
            }
            set
            {
                synthesizeReplaceEnabled = value;
            }
        }

        public override int Ordinal
        {
            get
            {
                return 1;
            }
        }

        public bool IsPlaying
        {
            get
            {
                return playing;
            }
        }        

        #endregion

        #endregion

        #region IProgrammable Members

        public string GetParameterName(int index)
        {
            #region Require

            if(index < 0 || index >= ParameterCount)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            #endregion

            string result = string.Empty;
            string name = Name;

            if(!string.IsNullOrEmpty(name))
            {
                name = name + " ";
            }

            switch((ParameterId)index)
            {
                case ParameterId.Panning:
                    result = name + "Panning";
                    break;

                case ParameterId.WaveformType:
                    result = name + "Waveform";
                    break;

                default:
                    Debug.Fail("Unhandled parameter.");
                    break;
            }

            return result;
        }

        public string GetParameterLabel(int index)
        {
            #region Require

            if(index < 0 || index >= ParameterCount)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            #endregion

            string result = string.Empty;

            switch((ParameterId)index)
            {
                case ParameterId.Panning:
                    result = "Left/Right";
                    break;

                case ParameterId.WaveformType:
                    result = "Type";
                    break;

                default:
                    Debug.Fail("Unhandled parameter.");
                    break;
            }

            return result;
        }

        public string GetParameterDisplay(int index)
        {
            #region Require

            if(index < 0 || index >= ParameterCount)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            #endregion

            string result = string.Empty;

            switch((ParameterId)index)
            {
                case ParameterId.Panning:
                    {
                        float position = panning * 2 - 1;

                        result = position.ToString("F");
                    }
                    break;

                case ParameterId.WaveformType:
                    result = waveType.ToString();
                    break;

                default:
                    Debug.Fail("Unhandled parameter.");
                    break;
            }

            return result;
        }

        public float GetParameterValue(int index)
        {
            #region Require

            if(index < 0 || index >= ParameterCount)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            #endregion

            float result = 0;

            switch((ParameterId)index)
            {
                case ParameterId.Panning:
                    result = panning;
                    break;

                case ParameterId.WaveformType:
                    result = (float)(int)waveType / (WaveformTypeCount - 1);
                    break;

                default:
                    Debug.Fail("Unhandled parameter.");
                    break;
            }

            return result;
        }

        public void SetParameterValue(int index, float value)
        {
            #region Require

            if(index < 0 || index >= ParameterCount)
            {
                throw new ArgumentOutOfRangeException("index");
            }
            else if(value < 0 || value > 1)
            {
                throw new ArgumentOutOfRangeException("value");
            }

            #endregion

            switch((ParameterId)index)
            {
                case ParameterId.Panning:
                    panning = value;
                    break;

                case ParameterId.WaveformType:
                    waveType = (WaveformType)(int)Math.Round(value * (WaveformTypeCount - 1));
                    break;

                default:
                    Debug.Fail("Unhandled parameter.");
                    break;
            }
        }

        public int ParameterCount
        {
            get
            {
                return (int)ParameterId.WaveformType + 1;
            }
        }

        #endregion

        #region IBendable Members

        public float PitchBendModulation
        {
            get
            {
                return pitchBendModulation;
            }
            set
            {
                pitchBendModulation = value;
            }
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
United States United States
Aside from dabbling in BASIC on his old Atari 1040ST years ago, Leslie's programming experience didn't really begin until he discovered the Internet in the late 90s. There he found a treasure trove of information about two of his favorite interests: MIDI and sound synthesis.

After spending a good deal of time calculating formulas he found on the Internet for creating new sounds by hand, he decided that an easier way would be to program the computer to do the work for him. This led him to learn C. He discovered that beyond using programming as a tool for synthesizing sound, he loved programming in and of itself.

Eventually he taught himself C++ and C#, and along the way he immersed himself in the ideas of object oriented programming. Like many of us, he gotten bitten by the design patterns bug and a copy of GOF is never far from his hands.

Now his primary interest is in creating a complete MIDI toolkit using the C# language. He hopes to create something that will become an indispensable tool for those wanting to write MIDI applications for the .NET framework.

Besides programming, his other interests are photography and playing his Les Paul guitars.

Comments and Discussions