Ejemplo n.º 1
0
        public WaveGenerator(WaveExampleType type)
        {
            _header = new WaveHeader();
            _format = new WaveFormatChunk();
            _data   = new WaveDataChunk();

            switch (type)
            {
            case WaveExampleType.ExampleSineWave:
                uint numSamples = _format.SamplesPerSec * _format.NumberOfChannels;
                _data.ShortArray = new short[numSamples];
                int    amplitude = 32760;
                double freq      = 440.0f;
                double t         = (Math.PI * 2 * freq) / (_format.SamplesPerSec * _format.NumberOfChannels);

                for (uint i = 0; i < numSamples - 1; i++)
                {
                    for (int channel = 0; channel < _format.NumberOfChannels; channel++)
                    {
                        _data.ShortArray[i + channel] = Convert.ToInt16(amplitude * Math.Sin(t * i));
                    }
                }

                _data.LenghtOfHeaderInBytes = (uint)(_data.ShortArray.Length * (_format.BitsPerSample / 8));

                break;
            }
        }
Ejemplo n.º 2
0
        public WaveGenerator(WaveExampleType type)
        {
            // Init chunks
            header = new WaveHeader();
            format = new WaveFormatChunk();
            data   = new WaveDataChunk();
            // Fill the data array with sample data
            switch (type)
            {
            case WaveExampleType.ExampleSineWave:
                // Number of samples = sample rate * channels * bytes per sample
                uint numSamples = format.dwSamplesPerSec * format.wChannels;
                // Initialize the 16-bit array
                data.shortArray = new short[numSamples];
                int    amplitude = 32760;      // Max amplitude for 16-bit audio
                double freq      = 440.0f;     // Concert A: 440Hz
                // The "angle" used in the function, adjusted for the number of channels and sample rate.
                // This value is like the period of the wave.
                double t = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);
                for (uint i = 0; i < numSamples - 1; i++)
                {
                    // Fill with a simple sine wave at max amplitude
                    for (int channel = 0; channel < format.wChannels; channel++)
                    {
                        data.shortArray[i + channel] = Convert.ToInt16(amplitude * Math.Sin(t * i));
                    }
                }



                // Calculate data chunk size in bytes
                data.dwChunkSize = (uint)(data.shortArray.Length * (format.wBitsPerSample / 8));
                break;
            }
        }
Ejemplo n.º 3
0
        // Function overloaded
        public WaveGenerator(WaveExampleType type, List <byte> waveData)
        {
            // Initialize chunks:
            byte bite = 1;

            header = new WaveHeader();
            format = new WaveFormatChunk(bite);
            data   = new WaveDataChunk(bite);

            // Initialize the 8-bit array
            data.byteArray = new byte [waveData.Count];

            // Copy the data
            for (int i = 0; i < data.byteArray.Length; i++)
            {
                if (i < waveData.Count)
                {
                    data.byteArray[i] = waveData[i];
                }
                else
                {
                    data.byteArray[i] = 0;
                }
            }

            // Calculate data chunk size in bytes.
            // The data chunk needs the bitrate which is stored in the format chunk,
            // so this needs to be set manually.
            data.dwChunkSize = (uint)(data.byteArray.Length * (format.wBitsPerSample / 8));
        }
        public WaveGenerator(WaveExampleType type, double frequency)
        {
            //initialize
            header = new WaveHeader();
            format = new WaveFormatChunk();
            data = new WaveDataChunk();

            //set
            switch (type)
            {
                case WaveExampleType.ExampleSineWave:
                    uint samples = (format.dwSamplesPerSec * format.wChannels) * 5; //data
                    data.shortArray = new short[samples];
                    int amplitude = 32760;                                      //volume (out of 32760)
                    double freq = frequency;                                    //pitch in Hz
                    double t = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);
                    for (uint i = 0; i < samples - 1; i++)
                    {
                        for (int channels = 0; channels < format.wChannels; channels++)
                        {
                            data.shortArray[i + channels] = Convert.ToInt16(amplitude * Math.Sin(t * i));
                        }
                    }
                    data.dwChunkSize = (uint)(data.shortArray.Length * (format.wBitsPerSample / 8));
                    break;
            }
        }
Ejemplo n.º 5
0
        public static SoundPlayer ToSoundPlayer(this WaveExampleType type, int frequency, double volume)
        {
            WaveGenerator wave = new WaveGenerator(
                type,
                frequency,
                volume
                );

            var p = new SoundPlayer(wave);

            return(p);
        }
        public void playSound(WaveExampleType waveType)
        {
            // Set filepath
            string filePath = this.GetHashCode().ToString();

            // Instantiate wave generator
            WaveGenerator wave = new WaveGenerator(waveType, getFrequency(), 0.1);

            // Save to filepath
            wave.Save(filePath);

            // Play the sound
            player = new SoundPlayer(filePath);
            player.PlayLooping();
        }
Ejemplo n.º 7
0
        public WaveGenerator(WaveExampleType type)
        {
            // Init chunks
            header = new WaveHeader();
            format = new WaveFormatChunk();
            data = new WaveDataChunk();

            // Fill the data array with sample data
            switch (type)
            {
                case WaveExampleType.ExampleSineWave:

                    // Number of samples = sample rate * channels * bytes per sample
                    uint numSamples = format.dwSamplesPerSec * format.wChannels;

                    // Initialize the 16-bit array
                    data.shortArray = new short[numSamples];

                    int amplitude = 32760;  // Max amplitude for 16-bit audio
                    double freq = 440.0f;   // Concert A: 440Hz

                    // The "angle" used in the function, adjusted for the number of channels and sample rate.
                    // This value is like the period of the wave.
                    double t = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);

                    for (uint i = 0; i < numSamples - 1; i++)
                    {
                        // Fill with a simple sine wave at max amplitude
                        for (int channel = 0; channel < format.wChannels; channel++)
                        {
                            data.shortArray[i + channel] = Convert.ToInt16(amplitude * Math.Sin(t * i));
                        }
                    }

                    // Calculate data chunk size in bytes
                    data.dwChunkSize = (uint)(data.shortArray.Length * (format.wBitsPerSample / 8));

                    break;
            }
        }
        public WaveGenerator(WaveExampleType type)
        {
            header = new WaveHeader();
            format = new WaveFormatChunk();
            data   = new WaveDataChunk();

            switch (type)
            {
            case WaveExampleType.ExampleSineWave:

                //Number of samples = sample rate * channels * bytes per sample
                uint numSamples = format.dwSamplesPerSec * format.wChannels;

                //initialize the 16-bit array
                data.shortArray = new short[numSamples]; //initialize array length to numSamples?

                int    amplitude = 32760;                //Max Amplitude for 16 bit audio @ 32760 (because I know I'll inevitably turn it higher)
                double freq      = 440.0f;               //Concert A: 440 hz

                // The "angle" used in the function, adjusted for the number of channels and sample rate.
                // This value is like the period of the wave.
                double t = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);

                for (uint i = 0; i < numSamples - 1; i++)
                {
                    //Fill witha  simple sine wave at max amplitude
                    for (int channel = 0; channel < format.wChannels; channel++)
                    {
                        data.shortArray[i + channel] = Convert.ToInt16(amplitude * Math.Sin(t * i)); //isn't this just overwriting itself?
                    }                                                                                // With i @ 0 and channel at 1 shortarray[1] will be accessed then overwritten with i @ 1 and channel @ 0. F**k.
                }

                //calculate data chunk size in bytes
                data.dwChunkSize = (uint)(data.shortArray.Length * (format.wBitsPerSample / 8));

                break;
            }
        }
Ejemplo n.º 9
0
        public void addData(WaveExampleType type)
        {
            // Fill the data array with sample data

            uint   numSamples;
            int    amplitude;
            double freq, freq1, freq2;
            double t, t1, t2;
            double fCorr = -30f;

            switch (type)
            {
            case WaveExampleType.Low:
                numSamples = format.dwSamplesPerSec * format.wChannels / (int)(520.8333 * 2);
                amplitude  = 32760;     // Max amplitude for 16-bit audio
                freq       = (1562.5f) * 2;
                freq      -= fCorr;
                t          = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);
                for (uint i = offset; i < numSamples - 1 + offset; i++)
                {
                    for (int channel = 0; channel < format.wChannels; channel++)
                    {
                        data.shortArray.Add(Convert.ToInt16(amplitude * Math.Sin(t * i)));
                    }
                }
                data.dwChunkSize = (uint)(data.shortArray.Count * (format.wBitsPerSample / 8));
                break;

            case WaveExampleType.High:
                numSamples = format.dwSamplesPerSec * format.wChannels / (int)(520.8333 * 2);
                amplitude  = 32760;     // Max amplitude for 16-bit audio
                freq       = (2083f + (1 / 3)) * 2;
                freq      -= fCorr;
                t          = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);

                for (uint i = offset; i < numSamples - 1 + offset; i++)
                {
                    // Fill with a simple sine wave at max amplitude
                    for (int channel = 0; channel < format.wChannels; channel++)
                    {
                        data.shortArray.Add(Convert.ToInt16(amplitude * Math.Sin(t * i)));
                    }
                }
                // Calculate data chunk size in bytes
                data.dwChunkSize = (uint)(data.shortArray.Count * (format.wBitsPerSample / 8));
                break;

            case WaveExampleType.zero:
                numSamples = format.dwSamplesPerSec * format.wChannels;
                for (uint i = offset; i < numSamples - 1 + offset; i++)
                {
                    // Fill with a simple sine wave at max amplitude
                    for (int channel = 0; channel < format.wChannels; channel++)
                    {
                        data.shortArray.Add(0);
                    }
                }
                data.dwChunkSize = (uint)(data.shortArray.Count * (format.wBitsPerSample / 8));
                break;

            case WaveExampleType.broadcastCombined:
                numSamples = format.dwSamplesPerSec * format.wChannels;
                amplitude  = 32760 / 2;     // Max amplitude for 16-bit audio

                freq1  = (853f + (1 / 3)) * 2;
                freq1 -= fCorr;

                freq2  = (960f + (1 / 3)) * 2;
                freq2 -= fCorr;

                t1 = (Math.PI * 2 * freq1) / (format.dwSamplesPerSec * format.wChannels);
                t2 = (Math.PI * 2 * freq2) / (format.dwSamplesPerSec * format.wChannels);
                for (uint i = offset; i < numSamples - 1 + offset; i++)
                {
                    // Fill with a simple sine wave at max amplitude
                    for (int channel = 0; channel < format.wChannels; channel++)
                    {
                        data.shortArray.Add(Convert.ToInt16((amplitude * Math.Sin(t1 * i)) + (amplitude * Math.Sin(t2 * i))));
                    }
                }
                // Calculate data chunk size in bytes
                data.dwChunkSize = (uint)(data.shortArray.Count * (format.wBitsPerSample / 8));

                break;
            }
        }
Ejemplo n.º 10
0
 public static SoundPlayer ToSoundPlayer(this WaveExampleType type, int frequency)
 {
     return(type.ToSoundPlayer(frequency, 1));
 }
Ejemplo n.º 11
0
		/// <summary>
		/// Initializes the object and generates a wave.
		/// </summary>
		/// <param name="type">The type of wave to generate</param>
		public WaveGenerator(WaveExampleType type, int frequency, double volume)
		{
			// Init chunks
			header = new WaveHeader();
			format = new WaveFormatChunk();
			data = new WaveDataChunk();

			// Number of samples = sample rate * channels * bytes per sample
			uint numSamples = format.dwSamplesPerSec * format.wChannels;

			// Initialize the 16-bit array
			data.shortArray = new short[numSamples];
			data.shortArrayLength = numSamples;

			// Calculate data chunk size in bytes and store it in the data chunk
			data.dwChunkSize = (uint)(numSamples * (format.wBitsPerSample / 8));

			// Max amplitude for 16-bit audio
			int amplitude = (int)(MAX_AMPLITUDE_16BIT * volume);

			// Create a double version of the frequency for easier math
			double freq = (double)frequency;

			// The "angle" used in the function, adjusted for the number of channels and sample rate.
			// This value is like the period of the wave.
			double t = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);



			// Fill the data array with sample data

			if (type == WaveExampleType.ExampleSineWave)
			{
				ExampleSineWave(numSamples, amplitude, t);
				return;
			}

			if (type == WaveExampleType.ExampleSquareWave)
			{
				ExampleSquareWave(numSamples, amplitude, t);
				return;
			}

			if (type == WaveExampleType.ExampleWhiteNoise)
			{
				ExampleWhiteNoise(numSamples, amplitude);
				return;
			}

			if (type == WaveExampleType.ExampleSawtoothWave)
			{
				ExampleSawtoothWave(frequency, numSamples, amplitude);
				return;
			}


			if (type == WaveExampleType.ExampleTriangleWave)
			{
				ExampleTriangleWave(frequency, numSamples, amplitude);

				return;
			}




		}
Ejemplo n.º 12
0
        /// <summary>
        /// Initializes the object and generates a wave.
        /// </summary>
        /// <param name="type">The type of wave to generate</param>
        public WaveGenerator(WaveExampleType type, int frequency, double volume)
        {
            // Init chunks
            header = new WaveHeader();
            format = new WaveFormatChunk();
            data   = new WaveDataChunk();

            // Number of samples = sample rate * channels * bytes per sample
            uint numSamples = format.dwSamplesPerSec * format.wChannels;

            // Initialize the 16-bit array
            data.shortArray = new short[numSamples];

            // Calculate data chunk size in bytes and store it in the data chunk
            data.dwChunkSize = (uint)(data.shortArray.Length * (format.wBitsPerSample / 8));

            // Max amplitude for 16-bit audio
            int amplitude = (int)(MAX_AMPLITUDE_16BIT * volume);

            // Create a double version of the frequency for easier math
            double freq = (double)frequency;

            // The "angle" used in the function, adjusted for the number of channels and sample rate.
            // This value is like the period of the wave.
            double t = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);

            // Used to generate some of the linear waveforms
            int   samplesPerWavelength = 0;
            short ampStep    = 0;
            short tempSample = 0;

            // Fill the data array with sample data
            switch (type)
            {
            case WaveExampleType.ExampleSineWave:

                for (int i = 0; i < numSamples - 1; i++)
                {
                    // Fill with a simple sine wave at max amplitude
                    for (int channel = 0; channel < format.wChannels; channel++)
                    {
                        data.shortArray[i + channel] = Convert.ToInt16(amplitude * Math.Sin(t * i));
                    }
                }

                break;

            case WaveExampleType.ExampleSquareWave:

                for (int i = 0; i < numSamples - 1; i++)
                {
                    for (int channel = 0; channel < format.wChannels; channel++)
                    {
                        //data.shortArray[i] = Convert.ToInt16(amplitude * Math.Sign(Math.Sin(t * i)));
                        data.shortArray[i] = Convert.ToInt16(amplitude * Math.Sign(Math.Sin(t * i)));
                    }
                }
                break;

            case WaveExampleType.ExampleSawtoothWave:

                // Determine the number of samples per wavelength
                samplesPerWavelength = Convert.ToInt32(format.dwSamplesPerSec / (frequency / format.wChannels));

                // Determine the amplitude step for consecutive samples
                ampStep = Convert.ToInt16((amplitude * 2) / samplesPerWavelength);

                // Temporary sample value, added to as we go through the loop
                tempSample = (short)-amplitude;

                // Total number of samples written so we know when to stop
                int totalSamplesWritten = 0;

                while (totalSamplesWritten < numSamples)
                {
                    tempSample = (short)-amplitude;

                    for (uint i = 0; i < samplesPerWavelength && totalSamplesWritten < numSamples; i++)
                    {
                        for (int channel = 0; channel < format.wChannels; channel++)
                        {
                            tempSample += ampStep;
                            data.shortArray[totalSamplesWritten] = tempSample;

                            totalSamplesWritten++;
                        }
                    }
                }

                break;

            case WaveExampleType.ExampleTriangleWave:

                // Determine the number of samples per wavelength
                samplesPerWavelength = Convert.ToInt32(format.dwSamplesPerSec / (frequency / format.wChannels));

                // Determine the amplitude step for consecutive samples
                ampStep = Convert.ToInt16((amplitude * 2) / samplesPerWavelength);

                // Temporary sample value, added to as we go through the loop
                tempSample = (short)-amplitude;

                for (int i = 0; i < numSamples - 1; i++)
                {
                    for (int channel = 0; channel < format.wChannels; channel++)
                    {
                        // Negate ampstep whenever it hits the amplitude boundary
                        if (Math.Abs(tempSample) > amplitude)
                        {
                            ampStep = (short)-ampStep;
                        }

                        tempSample += ampStep;
                        data.shortArray[i + channel] = tempSample;
                    }
                }

                break;

            case WaveExampleType.ExampleWhiteNoise:

                // White noise is just a bunch of random samples.
                Random rnd         = new Random();
                short  randomValue = 0;

                // No need for a nested loop since it's all random anyway
                for (int i = 0; i < numSamples; i++)
                {
                    randomValue        = Convert.ToInt16(rnd.Next(-amplitude, amplitude));
                    data.shortArray[i] = randomValue;
                }

                break;
            }
        }
Ejemplo n.º 13
0
    public WaveGenerator(WaveExampleType type, float frequency, float volume, float duration)
    {
        //Cap parameters
        if (frequency < 200)
        {
            frequency = 200;
        }
        else if (frequency > 2000)
        {
            frequency = 1200;
        }
        if (volume < 0f)
        {
            volume = 0f;
        }
        else if (volume > 1f)
        {
            volume = 1f;
        }
        if (duration < 0)
        {
            duration = 0f;
        }
        else if (duration > 2.5f)
        {
            duration = 1.0f;
        }

        // Init chunks
        header = new WaveHeader();
        format = new WaveFormatChunk();
        data   = new WaveDataChunk();

        // Fill the data array with sample data
        switch (type)
        {
        case WaveExampleType.Sine:

            // Number of samples = duration * sample rate * channels * bytes per sample
            uint numSamples = (uint)(duration * format.dwSamplesPerSec * format.wChannels);

            // Initialize the 16-bit array
            data.shortArray = new short[numSamples];

            float amplitude = volume * 32760;     // Max amplitude for 16-bit audio
            if (frequency == 0)
            {
                frequency = 440.0f;                       // Concert A: 440Hz
            }
            // The "angle" used in the function, adjusted for the number of channels and sample rate.
            // This value is like the period of the wave.
            double t = (Math.PI * 2 * frequency) / (format.dwSamplesPerSec * format.wChannels);

            for (uint i = 0; i < numSamples - 1; i++)
            {
                // Fill with a simple sine wave at max amplitude
                for (int channel = 0; channel < format.wChannels; channel++)
                {
                    data.shortArray[i + channel] = Convert.ToInt16(amplitude * Math.Sin(t * i));
                }
            }

            // Calculate data chunk size in bytes
            data.dwChunkSize = (uint)(data.shortArray.Length * (format.wBitsPerSample / 8));

            break;
        } //switch
    }     //Constructor
Ejemplo n.º 14
0
        public WaveGenerator(WaveExampleType type)
        {
            // Init chunks
            header = new WaveHeader();
            format = type == WaveExampleType.MonoWave ? new WaveFormatChunk(false) : new WaveFormatChunk();
            data = new WaveDataChunk();

            // Fill the data array with sample data
            switch (type)
            {
                case WaveExampleType.ExampleSineWave:
                    {
                        // Number of samples = sample rate * channels * bytes per sample
                        uint numSamples = format.dwSamplesPerSec * format.wChannels;

                        // Initialize the 16-bit array
                        data.shortArray = new short[numSamples];

                        int amplitude = 32760; // Max amplitude for 16-bit audio
                        double freq = 440.0f; // Concert A: 440Hz

                        // The "angle" used in the function, adjusted for the number of channels and sample rate.
                        // This value is like the period of the wave.
                        double t = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);

                        for (uint i = 0; i < numSamples; i+=2)
                        {
                            // Fill in the stereo channels
                            short outp = Convert.ToInt16(amplitude * Math.Sin(t * i));
                            data.shortArray[i] = outp;
                            data.shortArray[i + 1] = outp;
                        }

                        // Calculate data chunk size in bytes
                        data.dwChunkSize = (uint)(data.shortArray.Length * (format.wBitsPerSample / 8));

                        break;
                    }
                case WaveExampleType.TetrisWave:
                    {
                        double[] tetrisNoteSequence =
                        {
                            WaveNoteFreq.E, WaveNoteFreq.B, WaveNoteFreq.C, WaveNoteFreq.D,
                            WaveNoteFreq.C, WaveNoteFreq.B, WaveNoteFreq.A, WaveNoteFreq.A,
                            WaveNoteFreq.C, WaveNoteFreq.E, WaveNoteFreq.D, WaveNoteFreq.C, WaveNoteFreq.B,
                            WaveNoteFreq.C, WaveNoteFreq.D, WaveNoteFreq.E, WaveNoteFreq.C, WaveNoteFreq.A
                        };

                        double[] tetrisNoteLength =
                        {
                            WaveNoteLength.Quarter, WaveNoteLength.Eighth, WaveNoteLength.Eighth, WaveNoteLength.Quarter,
                            WaveNoteLength.Eighth, WaveNoteLength.Eighth, WaveNoteLength.Quarter, WaveNoteLength.Eighth,
                            WaveNoteLength.Eighth, WaveNoteLength.Quarter, WaveNoteLength.Eighth, WaveNoteLength.Eighth, WaveNoteLength.ThreeQuarters,
                            WaveNoteLength.Eighth, WaveNoteLength.Quarter, WaveNoteLength.Quarter, WaveNoteLength.Quarter, WaveNoteLength.Half
                        };

                        double secondsLong = 0;
                        foreach (double noteLen in tetrisNoteLength)
                        {
                            secondsLong += noteLen;
                        }

                        // Number of samples = sample rate * channels * bytes per sample
                        uint numSamples = (uint)(format.dwSamplesPerSec * format.wChannels * secondsLong);

                        // Initialize the 16-bit array
                        data.shortArray = new short[numSamples];

                        // Max amplitude for 16-bit audio
                        int amplitude = 32760;

                        // Keep track of samples recorded
                        uint samplesRecorded = 0;

                        // Loop through each note
                        for (int i = 0; i < tetrisNoteSequence.Length; i++)
                        {
                            // The "angle" used in the function, adjusted for the number of channels and sample rate.
                            // This value is like the period of the wave.
                            double t = (Math.PI * 2 * tetrisNoteSequence[i]) / (format.dwSamplesPerSec * format.wChannels);

                            // The length in samples of the note
                            uint noteLengthSamples = (uint)(format.dwSamplesPerSec * format.wChannels * tetrisNoteLength[i]);

                            uint endTheNoteHere = samplesRecorded + noteLengthSamples;
                            for (uint j = samplesRecorded; j < endTheNoteHere - 1; j++)
                            {
                                // Convert to int16
                                short conv = Convert.ToInt16(amplitude * Math.Sin(t * j));

                                // Fill with a simple sine wave at max amplitude
                                for (int channel = 0; channel < format.wChannels; channel++)
                                {
                                    data.shortArray[j + channel] = conv;
                                }
                            }

                            samplesRecorded += noteLengthSamples;
                        }


                        // Calculate data chunk size in bytes
                        data.dwChunkSize = (uint)(data.shortArray.Length * (format.wBitsPerSample / 8));

                        break;
                    }
                case WaveExampleType.MessingWave:
                    {
                        // Number of samples = sample rate * channels * bytes per sample * seconds
                        uint numSamples = format.dwSamplesPerSec * format.wChannels * 40;

                        // Initialize the 16-bit array
                        data.shortArray = new short[numSamples];

                        int amplitude = 32760; // Max amplitude for 16-bit audio
                        double freq = 20.0f; // Concert A: 440Hz
                        double hz = 0.0009;

                        // Stereo volume interleave
                        double stereoInterleaveFreq = 0.5f;

                        // Channel amplitudes
                        double c = (Math.PI * 2 * stereoInterleaveFreq) / (format.dwSamplesPerSec * format.wChannels);

                        for (uint i = 0; i < numSamples - 1; i++)
                        {
                            // The "angle" used in the function, adjusted for the number of channels and sample rate.
                            // This value is like the period of the wave.
                            double t = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);
                            double s = Math.Sin(t * i);
                            double d = Math.Sin(c * i);
                            double channelAmp = amplitude * d;

                            // Fill with a simple sine wave at max amplitude
                            var sound = Convert.ToInt16(channelAmp * s);
                            data.shortArray[i] = sound; // Channel 1
                            data.shortArray[i + 1] = sound; // Channel 2

                            freq += hz;
                        }

                        // Calculate data chunk size in bytes
                        data.dwChunkSize = (uint)(data.shortArray.Length * (format.wBitsPerSample / 8));

                        break;
                    }
                case WaveExampleType.MonoWave:
                    {
                        // Number of samples = sample rate * channels * bytes per sample
                        uint numSamples = format.dwSamplesPerSec * format.wChannels;

                        // Initialize the 16-bit array
                        data.shortArray = new short[numSamples];

                        int amplitude = 32760; // Max amplitude for 16-bit audio
                        double freq = 40.0f; // Concert A: 440Hz

                        // The "angle" used in the function, adjusted for the number of channels and sample rate.
                        // This value is like the period of the wave.
                        double t = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);

                        for (uint i = 0; i < numSamples - 1; i++)
                        {
                            // Fill with a simple sine wave at max amplitude
                            for (int channel = 0; channel < format.wChannels; channel++)
                            {
                                data.shortArray[i + channel] = Convert.ToInt16(amplitude * Math.Sin(t * i));
                            }
                        }

                        // Calculate data chunk size in bytes
                        data.dwChunkSize = (uint)(data.shortArray.Length * (format.wBitsPerSample / 8));

                        break;
                    }
            }
        }
Ejemplo n.º 15
0
        private void AddNoteButton_Click(object sender, EventArgs e)
        {
            WaveExampleType[] selection = new WaveExampleType[3];
            for (int i = 0; i < 3; i++)
            {
                selection[i] = WaveExampleType.SineWave;
            }
            RadioButton[][] buttons = new RadioButton[3][];
            for (int i = 0; i < 3; i++)
            {
                buttons[i] = new RadioButton[6];
            }
            buttons[0][0] = SineButton1; buttons[0][1] = SquareButton1; buttons[0][2] = SawtoothButton1; buttons[0][3] = TriangleButton1; buttons[0][4] = WhiteButton1; buttons[0][5] = NothingButton1;
            buttons[1][0] = SineButton2; buttons[1][1] = SquareButton2; buttons[1][2] = SawtoothButton2; buttons[1][3] = TriangleButton2; buttons[1][4] = WhiteButton2; buttons[1][5] = NothingButton2;
            buttons[2][0] = SineButton3; buttons[2][1] = SquareButton3; buttons[2][2] = SawtoothButton3; buttons[2][3] = TriangleButton3; buttons[2][4] = WhiteButton3; buttons[2][5] = NothingButton3;
            for (int i = 0; i < 3; i++)
            {
                if (buttons[i][0].Checked)
                {
                    selection[i] = WaveExampleType.SineWave;
                }
                else if (buttons[i][1].Checked)
                {
                    selection[i] = WaveExampleType.SquareWave;
                }
                else if (buttons[i][2].Checked)
                {
                    selection[i] = WaveExampleType.SawtoothWave;
                }
                else if (buttons[i][3].Checked)
                {
                    selection[i] = WaveExampleType.TriangleWave;
                }
                else if (buttons[i][4].Checked)
                {
                    selection[i] = WaveExampleType.WhiteNoise;
                }
                else if (buttons[i][5].Checked)
                {
                    selection[i] = WaveExampleType.Nothing;
                }
                else
                {
                    selection[i] = WaveExampleType.Nothing;
                }
            }

            /* Find the frequency of each note */
            double[]   frequency        = new double[3];
            TrackBar[] octaveSliders    = new TrackBar[3];
            TrackBar[] frequencySliders = new TrackBar[3];
            octaveSliders[0]    = OctaveSlider1; octaveSliders[1] = OctaveSlider2; octaveSliders[2] = OctaveSlider3;
            frequencySliders[0] = FrequencySlider1; frequencySliders[1] = FrequencySlider2; frequencySliders[2] = FrequencySlider3;
            for (int i = 0; i < 3; i++)
            {
                double power      = octaveSliders[i].Value - 3;
                double multiplier = Math.Pow(2, power);
                frequency[i] = Notes[frequencySliders[i].Value] * multiplier;
            }

            /* Find the amplitude of each note */
            int[]      volume        = new int[3];
            TrackBar[] volumeSliders = new TrackBar[3];
            volumeSliders[0] = VolumeSlider1; volumeSliders[1] = VolumeSlider2; volumeSliders[2] = VolumeSlider3;
            for (int i = 0; i < 3; i++)
            {
                volume[i] = volumeSliders[i].Value * (VolMax / 10);
            }

            /* Find the ADSR times */
            double[] ADSRtime     = new double[6];
            float    clipDuration = 0;

            foreach (System.Windows.Forms.Control control in this.DurationGroupBox.Controls)
            {
                System.Windows.Forms.RadioButton button = (System.Windows.Forms.RadioButton)control;
                if (button.Checked)
                {
                    clipDuration = float.Parse(button.Tag.ToString(), CultureInfo.InvariantCulture.NumberFormat) / (this.BPM / 60);
                }
            }
            ADSRtime[0] = 0;
            ADSRtime[1] = AttackTime.Value * (clipDuration / 1000) * 44100;
            ADSRtime[2] = DecayTime.Value * (clipDuration / 1000) * 44100;
            ADSRtime[3] = SustainTime.Value * (clipDuration / 1000) * 44100;
            ADSRtime[4] = ReleaseTime.Value * (clipDuration / 1000) * 44100;
            ADSRtime[5] = clipDuration * 44100;

            /* Find the ADSR amplitudes */
            double[] ADSRvolume = new double[4];
            ADSRvolume[0] = (float)AttackAmplitude.Value / 100;
            ADSRvolume[1] = (float)DecayAmplitude.Value / 100;
            ADSRvolume[2] = (float)SustainAmplitude.Value / 100;
            ADSRvolume[3] = (float)ReleaseAmplitude.Value / 100;

            string        filePath = Directory.GetCurrentDirectory() + "\\sound.wav";
            WaveGenerator wave     = new WaveGenerator(false);

            wave.makeNote(selection,
                          frequency,
                          volume,
                          clipDuration,
                          ADSRtime,
                          ADSRvolume
                          );

            /* Show what the final plot looks like */
            UpdateSoundWaveChart(wave.getNumSamples(), wave.getData());

            /* Add the note to the correct track */
            song.AddNote(wave.getData(), TrackIndex[0]);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Initializes the object and generates a wave.
        /// </summary>
        /// <param name="type">The type of wave to generate</param>
        public WaveGenerator(WaveExampleType type, int frequency, double volume)
        {
            // Init chunks
            header = new WaveHeader();
            format = new WaveFormatChunk();
            data   = new WaveDataChunk();

            // Number of samples = sample rate * channels * bytes per sample
            uint numSamples = format.dwSamplesPerSec * format.wChannels;

            // Initialize the 16-bit array
            data.shortArray       = new short[numSamples];
            data.shortArrayLength = numSamples;

            // Calculate data chunk size in bytes and store it in the data chunk
            data.dwChunkSize = (uint)(numSamples * (format.wBitsPerSample / 8));

            // Max amplitude for 16-bit audio
            int amplitude = (int)(MAX_AMPLITUDE_16BIT * volume);

            // Create a double version of the frequency for easier math
            double freq = (double)frequency;

            // The "angle" used in the function, adjusted for the number of channels and sample rate.
            // This value is like the period of the wave.
            double t = (Math.PI * 2 * freq) / (format.dwSamplesPerSec * format.wChannels);



            // Fill the data array with sample data

            if (type == WaveExampleType.ExampleSineWave)
            {
                ExampleSineWave(numSamples, amplitude, t);
                return;
            }

            if (type == WaveExampleType.ExampleSquareWave)
            {
                ExampleSquareWave(numSamples, amplitude, t);
                return;
            }

            if (type == WaveExampleType.ExampleWhiteNoise)
            {
                ExampleWhiteNoise(numSamples, amplitude);
                return;
            }

            if (type == WaveExampleType.ExampleSawtoothWave)
            {
                ExampleSawtoothWave(frequency, numSamples, amplitude);
                return;
            }


            if (type == WaveExampleType.ExampleTriangleWave)
            {
                ExampleTriangleWave(frequency, numSamples, amplitude);

                return;
            }
        }