Click here to Skip to main content
15,884,176 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 237.9K   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.Diagnostics;
using Sanford.Multimedia.Wave;

namespace Sanford.Multimedia.Synth
{
    /// <summary>
    /// Represents a buffer of stereo waveform data.
    /// </summary>
    public class StereoBuffer : IProgrammable
    {
        #region StereoBuffer

        #region Enumerations

        public enum ParameterId
        {
            Amplitude
        }

        #endregion

        #region Fields

        // For holding the stereo waveform data.
        private float[,] buffer;

        // Used for modulating the buffer's amplitude.
        private float amplitude = 0.25f;

        #endregion

        #region Events

        /// <summary>
        /// Occurs when the value of the BufferSize property changes.
        /// </summary>
        public event EventHandler BufferSizeChanged;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the StereoBuffer class with 
        /// the specified buffer size.
        /// </summary>
        /// <param name="bufferSize">
        /// The size of the buffer.
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// bufferSize is less than zero.
        /// </exception>
        public StereoBuffer(int bufferSize)
        {
            #region Require

            if(bufferSize < 0)
            {
                throw new ArgumentOutOfRangeException("bufferSize");
            }

            #endregion

            // Create a two dimensional array, one dimension for each channel, 
            // left and right.
            buffer = new float[2, bufferSize];
        }

        #endregion

        #region Methods

        /// <summary>
        /// Clears the buffer of its contents.
        /// </summary>
        public void Clear()
        {
            int bufferSize = BufferSize;

            for(int i = 0; i < bufferSize; i++)
            {
                buffer[0, i] = buffer[1, i] = 0; 
            }
        }

        /// <summary>
        /// Gets the underlying two dimensional array representing the buffer.
        /// </summary>
        /// <returns>
        /// The underlying two dimensional array representing the buffer.
        /// </returns>
        public float[,] GetBuffer()
        {
            return buffer;
        }

        /// <summary>
        /// Modulates the amplitude of the buffer by the amplitude value.
        /// </summary>
        internal void ModulateAmplitude()
        {
            int bufferSize = BufferSize;

            for(int i = 0; i < bufferSize; i++)
            {
                buffer[0, i] *= amplitude;
                buffer[1, i] *= amplitude;
            }
        }

        /// <summary>
        /// Gets the left channel peak.
        /// </summary>
        /// <returns>
        /// The left channel peak.
        /// </returns>
        internal float GetLeftPeak()
        {
            return GetPeak(0);
        }

        /// <summary>
        /// Gets the right channel peak.
        /// </summary>
        /// <returns>
        /// The right channel peak.
        /// </returns>
        internal float GetRightPeak()
        {
            return GetPeak(1);
        }

        private float GetPeak(int channel)
        {
            int bufferSize = BufferSize;
            float result = 0;
            float sample;

            for(int i = 0; i < bufferSize; i++)
            {
                sample = Math.Abs(buffer[channel, i]);

                if(sample > result)
                {
                    result = sample;
                }
            }

            return result;
        }

        /// <summary>
        /// Writes the buffer's contents to a waveform OutputBuffer.
        /// </summary>
        /// <param name="buffer">
        /// The OutputBufer this buffer will be written to.
        /// </param>
        internal void WriteToOutputBuffer(WaveformBuffer buffer)
        {
            Debug.Assert(buffer != null);
            Debug.Assert(buffer.Length >= BufferSize * Synthesizer.BlockAlign, "WaveformBuffer is too small.");

            int bufferSize = BufferSize;
            int n = 0;
            short sample;

            //
            // For every value in the buffer, multiply short.MaxValue by 
            // the buffer value to get a 16-bit sample. Then break the sample into 
            // two bytes and assign each byte in turn to the waveform
            // OutputBuffer.
            //

            for(int i = 0; i < bufferSize; i++)
            {
                //
                // Left channel.
                //

                sample = (short)(short.MaxValue * this.buffer[0, i]);
                buffer[n] = (byte)sample;
                n++;
                buffer[n] = (byte)(sample >> 8);
                n++;

                //
                // Right channel.
                //

                sample = (short)(short.MaxValue * this.buffer[1, i]);
                buffer[n] = (byte)sample;
                n++;
                buffer[n] = (byte)(sample >> 8);
                n++;
            }
        }

        protected virtual void OnBufferSizeChanged(EventArgs e)
        {
            EventHandler handler = BufferSizeChanged;

            if(handler != null)
            {
                handler(this, e);
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the buffer size.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">
        /// BufferSize is set to a value less than zero.
        /// </exception>
        public int BufferSize
        {
            get
            {
                return buffer.GetLength(1);
            }
            set
            {
                #region Require

                if(value < 0)
                {
                    throw new ArgumentOutOfRangeException("value");
                }

                #endregion

                #region Guard

                if(value == buffer.GetLength(1))
                {
                    return;
                }

                #endregion

                buffer = new float[2, value];

                OnBufferSizeChanged(EventArgs.Empty);
            }
        }

        #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;

            switch((ParameterId)index)
            {
                case ParameterId.Amplitude:
                    result = "Amplitude";
                    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.Amplitude:
                    result = "dB";
                    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.Amplitude:
                    result = Synthesizer.DecibelToString(amplitude);
                    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.Amplitude:
                    result = amplitude;
                    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.Amplitude:
                    amplitude = value;
                    break;

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

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

        #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