声音合成器 1 基本噪音
视频:https://www.bilibili.com/video/BV14z4y1r7wX?p=6
代码:https://github.com/OneLoneCoder/synth
一、准备工作
1.创建空工程,设置工程属性。链接器--输入--附加依赖项中添加winmm.lib;

2.在项目中添加头文件:olcNoiseMaker.h
https://github.com/OneLoneCoder/synth/blob/master/olcNoiseMaker.h
/* OneLoneCoder.com - Simple Audio Noisy Thing"Allows you to simply listen to that waveform!" - @Javidx9License~~~~~~~Copyright (C) 2018 Javidx9This program comes with ABSOLUTELY NO WARRANTY.This is free software, and you are welcome to redistribute itunder certain conditions; See license for details. Original works located at:https://www.github.com/onelonecoderhttps://www.onelonecoder.comhttps://www.youtube.com/javidx9GNU GPLv3https://github.com/OneLoneCoder/videos/blob/master/LICENSEFrom Javidx9 :)~~~~~~~~~~~~~~~Hello! Ultimately I don't care what you use this for. It's intended to be educational, and perhaps to the oddly minded - a little bit of fun. Please hack this, change it and use it in any way you see fit. You acknowledge that I am not responsible for anything bad that happens as a result of your actions. However this code is protected by GNU GPLv3, see the license in thegithub repo. This means you must attribute me if you use it. You can view thislicense here: https://github.com/OneLoneCoder/videos/blob/master/LICENSECheers!Author~~~~~~Twitter: @javidx9Blog: www.onelonecoder.comVersions~~~~~~~~1.0 - 14/01/17- Controls audio output hardware behind the scenes so you can just focuson creating and listening to interesting waveforms.- Currently MS Windows onlyDocumentation~~~~~~~~~~~~~See video: https://youtu.be/tgamhuQnOkMThis will improve as it grows!
*/#pragma once#pragma comment(lib, "winmm.lib")#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;#include const double PI = 2.0 * acos(0.0);template
class olcNoiseMaker
{
public:olcNoiseMaker(wstring sOutputDevice, unsigned int nSampleRate = 44100, unsigned int nChannels = 1, unsigned int nBlocks = 8, unsigned int nBlockSamples = 512){Create(sOutputDevice, nSampleRate, nChannels, nBlocks, nBlockSamples);}~olcNoiseMaker(){Destroy();}bool Create(wstring sOutputDevice, unsigned int nSampleRate = 44100, unsigned int nChannels = 1, unsigned int nBlocks = 8, unsigned int nBlockSamples = 512){m_bReady = false;m_nSampleRate = nSampleRate;m_nChannels = nChannels;m_nBlockCount = nBlocks;m_nBlockSamples = nBlockSamples;m_nBlockFree = m_nBlockCount;m_nBlockCurrent = 0;m_pBlockMemory = nullptr;m_pWaveHeaders = nullptr;m_userFunction = nullptr;// Validate devicevector devices = Enumerate();auto d = std::find(devices.begin(), devices.end(), sOutputDevice);if (d != devices.end()){// Device is availableint nDeviceID = distance(devices.begin(), d);WAVEFORMATEX waveFormat;waveFormat.wFormatTag = WAVE_FORMAT_PCM;waveFormat.nSamplesPerSec = m_nSampleRate;waveFormat.wBitsPerSample = sizeof(T) * 8;waveFormat.nChannels = m_nChannels;waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels;waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;waveFormat.cbSize = 0;// Open Device if validif (waveOutOpen(&m_hwDevice, nDeviceID, &waveFormat, (DWORD_PTR)waveOutProcWrap, (DWORD_PTR)this, CALLBACK_FUNCTION) != S_OK)return Destroy();}// Allocate Wave|Block Memorym_pBlockMemory = new T[m_nBlockCount * m_nBlockSamples];if (m_pBlockMemory == nullptr)return Destroy();ZeroMemory(m_pBlockMemory, sizeof(T) * m_nBlockCount * m_nBlockSamples);m_pWaveHeaders = new WAVEHDR[m_nBlockCount];if (m_pWaveHeaders == nullptr)return Destroy();ZeroMemory(m_pWaveHeaders, sizeof(WAVEHDR) * m_nBlockCount);// Link headers to block memoryfor (unsigned int n = 0; n < m_nBlockCount; n++){m_pWaveHeaders[n].dwBufferLength = m_nBlockSamples * sizeof(T);m_pWaveHeaders[n].lpData = (LPSTR)(m_pBlockMemory + (n * m_nBlockSamples));}m_bReady = true;m_thread = thread(&olcNoiseMaker::MainThread, this);// Start the ball rollingunique_lock lm(m_muxBlockNotZero);m_cvBlockNotZero.notify_one();return true;}bool Destroy(){return false;}void Stop(){m_bReady = false;m_thread.join();}// Override to process current samplevirtual double UserProcess(double dTime){return 0.0;}double GetTime(){return m_dGlobalTime;}public:static vector Enumerate(){int nDeviceCount = waveOutGetNumDevs();vector sDevices;WAVEOUTCAPS woc;for (int n = 0; n < nDeviceCount; n++)if (waveOutGetDevCaps(n, &woc, sizeof(WAVEOUTCAPS)) == S_OK)sDevices.push_back(woc.szPname);return sDevices;}void SetUserFunction(double(*func)(double)){m_userFunction = func;}double clip(double dSample, double dMax){if (dSample >= 0.0)return fmin(dSample, dMax);elsereturn fmax(dSample, -dMax);}private:double(*m_userFunction)(double);unsigned int m_nSampleRate;unsigned int m_nChannels;unsigned int m_nBlockCount;unsigned int m_nBlockSamples;unsigned int m_nBlockCurrent;T* m_pBlockMemory;WAVEHDR *m_pWaveHeaders;HWAVEOUT m_hwDevice;thread m_thread;atomic m_bReady;atomic m_nBlockFree;condition_variable m_cvBlockNotZero;mutex m_muxBlockNotZero;atomic m_dGlobalTime;// Handler for soundcard request for more datavoid waveOutProc(HWAVEOUT hWaveOut, UINT uMsg, DWORD dwParam1, DWORD dwParam2){if (uMsg != WOM_DONE) return;m_nBlockFree++;unique_lock lm(m_muxBlockNotZero);m_cvBlockNotZero.notify_one();}// Static wrapper for sound card handlerstatic void CALLBACK waveOutProcWrap(HWAVEOUT hWaveOut, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2){((olcNoiseMaker*)dwInstance)->waveOutProc(hWaveOut, uMsg, dwParam1, dwParam2);}// Main thread. This loop responds to requests from the soundcard to fill 'blocks'// with audio data. If no requests are available it goes dormant until the sound// card is ready for more data. The block is fille by the "user" in some manner// and then issued to the soundcard.void MainThread(){m_dGlobalTime = 0.0;double dTimeStep = 1.0 / (double)m_nSampleRate;// Goofy hack to get maximum integer for a type at run-timeT nMaxSample = (T)pow(2, (sizeof(T) * 8) - 1) - 1;double dMaxSample = (double)nMaxSample;T nPreviousSample = 0;while (m_bReady){// Wait for block to become availableif (m_nBlockFree == 0){unique_lock lm(m_muxBlockNotZero);m_cvBlockNotZero.wait(lm);}// Block is here, so use itm_nBlockFree--;// Prepare block for processingif (m_pWaveHeaders[m_nBlockCurrent].dwFlags & WHDR_PREPARED)waveOutUnprepareHeader(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR));T nNewSample = 0;int nCurrentBlock = m_nBlockCurrent * m_nBlockSamples;for (unsigned int n = 0; n < m_nBlockSamples; n++){// User Processif (m_userFunction == nullptr)nNewSample = (T)(clip(UserProcess(m_dGlobalTime), 1.0) * dMaxSample);elsenNewSample = (T)(clip(m_userFunction(m_dGlobalTime), 1.0) * dMaxSample);m_pBlockMemory[nCurrentBlock + n] = nNewSample;nPreviousSample = nNewSample;m_dGlobalTime = m_dGlobalTime + dTimeStep;}// Send block to sound devicewaveOutPrepareHeader(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR));waveOutWrite(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR));m_nBlockCurrent++;m_nBlockCurrent %= m_nBlockCount;}}
};
二、开始制造噪音
这里有一些和声音采样有关的知识,当然不知道也不影响继续。
2.1 声音测试(建议把声音先调低点,运行后应该听到呜呜的噪声)
#include
using namespace std;#include "olcNoiseMaker.h"double MakeNoise(double dTime)
{return 0.5*sin(440.0 * 2 * 3.14159*dTime); //声音的频率440hz
}int main()
{// Shameless self-promotionwcout << "www.OneLoneCoder.com - Synthesizer Part 1" << endl << "Single Sine Wave Oscillator, No Polyphony" << endl << endl;// Get all sound hardwarevector devices = olcNoiseMaker::Enumerate();// Display findingsfor (auto d : devices) wcout << "Found Output Device: " << d << endl;wcout << "Using Device: " << devices[0] << endl;//创建声音机器olcNoiseMaker sound(devices[0], 44100, 1, 8, 512); //44100~奈奎斯特采样(记录的最高频率2倍),sound.SetUserFunction(MakeNoise);while (1){}return 0;
}
2.2 控制声音
通过按键‘a’更改频率,来改变声音。
atomic dFreequencyOutput = 0.0; //原子类,用来保证多进程同步double MakeNoise(double dTime)
{//方波double dOutput = 1.0*sin(dFreequencyOutput * 2 * 3.14159*dTime);if (dOutput > 0.0)return 0.2;elsereturn -0.2;
}while (1){//按键响应'a'if (GetAsyncKeyState('A') & 0x8000){dFreequencyOutput = 440.0;}else {dFreequencyOutput = 0;}}
更准确一些可以将一个基本音分为12个组...
double dOctaveBaseFrequency = 110.0; // A2 // frequency of octave represented by keyboarddouble d12thRootOf2 = pow(2.0, 1.0 / 12.0); // assuming western 12 notes per ocatvewhile (1){//按键响应'a'if (GetAsyncKeyState('A') & 0x8000){dFreequencyOutput = dOctaveBaseFrequency * pow(d12thRootOf2,12);}else {dFreequencyOutput = 0;}}
然后利用16个键来控制不同的调。
bool bKeyPressed = false;for (int k = 0; k < 15; k++){if (GetAsyncKeyState((unsigned char)("ZSXCFVGBNJMK\xbcL\xbe\xbf"[k])) & 0x8000){dFreequencyOutput = dOctaveBaseFrequency * pow(d12thRootOf2, k);bKeyPressed = true;}}if(!bKeyPressed){dFreequencyOutput = 0.0;}
2.3 完整代码,最后说的和弦没有做出来
#include
using namespace std;#include "olcNoiseMaker.h"atomic dFreequencyOutput = 0.0; //原子类,用来保证多进程同步double MakeNoise(double dTime)
{//方波double dOutput = 1.0*sin(dFreequencyOutput * 2 * 3.14159*dTime);if (dOutput > 0.0)return 0.2;elsereturn -0.2;
}int main()
{// Shameless self-promotionwcout << "www.OneLoneCoder.com - Synthesizer Part 1" << endl << "Single Sine Wave Oscillator, No Polyphony" << endl << endl;// Get all sound hardwarevector devices = olcNoiseMaker::Enumerate();// Display findingsfor (auto d : devices) wcout << "Found Output Device: " << d << endl;wcout << "Using Device: " << devices[0] << endl;//创建声音机器olcNoiseMaker sound(devices[0], 44100, 1, 8, 512); //44100~奈奎斯特采样(记录的最高频率2倍),sound.SetUserFunction(MakeNoise);double dOctaveBaseFrequency = 110.0; // A2 // frequency of octave represented by keyboarddouble d12thRootOf2 = pow(2.0, 1.0 / 12.0); // assuming western 12 notes per ocatvewhile (1){bool bKeyPressed = false;for (int k = 0; k < 15; k++){if (GetAsyncKeyState((unsigned char)("ZSXCFVGBNJMK\xbcL\xbe\xbf"[k])) & 0x8000){dFreequencyOutput = dOctaveBaseFrequency * pow(d12thRootOf2, k);bKeyPressed = true;}}if(!bKeyPressed){dFreequencyOutput = 0.0;}}return 0;
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
