DWinProgramming /Samples/Chap22/AddSynth/AddSynth.d

Language D Lines 308
MD5 Hash 0de3cbfe043519f6602127cfbbf00488
Repository git://github.com/AndrejMitrovic/DWinProgramming.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/+
 + Copyright (c) Charles Petzold, 1998.
 + Ported to the D Programming Language by Andrej Mitrovic, 2011.
 +/

module AddSynth;

import core.memory;
import core.runtime;
import core.thread;
import std.array : replicate;
import std.conv;
import std.math;
import std.range;
import std.string;
import std.exception;
import std.stdio;
import std.utf;

auto toUTF16z(S)(S s)
{
    return toUTFz!(const(wchar)*)(s);
}

pragma(lib, "gdi32.lib");
pragma(lib, "comdlg32.lib");
pragma(lib, "winmm.lib");
import win32.windef;
import win32.winuser;
import win32.wingdi;
import win32.winbase;
import win32.commdlg;
import win32.mmsystem;

import resource;
import WaveTable;

string appName     = "AddSynth";
string description = "AddSynth";
HINSTANCE hinst;

extern (Windows)
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow)
{
    int result;
    void exceptionHandler(Throwable e) { throw e; }

    try
    {
        Runtime.initialize(&exceptionHandler);
        result = myWinMain(hInstance, hPrevInstance, lpCmdLine, iCmdShow);
        Runtime.terminate(&exceptionHandler);
    }
    catch (Throwable o)
    {
        MessageBox(null, o.toString().toUTF16z, "Error", MB_OK | MB_ICONEXCLAMATION);
        result = 0;
    }

    return result;
}

int myWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow)
{
    if (DialogBox(hInstance, appName.toUTF16z, NULL, &DlgProc) == -1)
    {
        MessageBox(NULL, "This program requires Windows NT!", appName.toUTF16z, MB_ICONERROR);
    }

    return 0;
}

enum ID_TIMER     = 1;
enum SAMPLE_RATE  = 22050;
enum MAX_PARTIALS = 21;

double SineGenerator(double dFreq, ref double pdAngle)
{
    double dAmp;

    dAmp      = sin(pdAngle);
    pdAngle  += 2 * PI * dFreq / SAMPLE_RATE;

    if (pdAngle >= 2 * PI)
        pdAngle -= 2 * PI;

    return dAmp;
}

// Fill a buffer with a composite waveform
VOID FillBuffer(INS ins, ref PBYTE pBuffer, int iNumSamples)
{
    static double[MAX_PARTIALS] dAngle;
    dAngle[] = 0.0;
    
    double dAmp, dFrq, dComp, dFrac;
    int i, iPrt, iMsecTime, iCompMaxAmp, iMaxAmp, iSmp;

    // Calculate the composite maximum amplitude
    iCompMaxAmp = 0;

    for (iPrt = 0; iPrt < ins.pprt.length; iPrt++)
    {
        iMaxAmp = 0;

        for (i = 0; i < ins.pprt[iPrt].ampArray.length; i++)
            iMaxAmp = max(iMaxAmp, ins.pprt[iPrt].ampArray[i].iValue);

        iCompMaxAmp += iMaxAmp;
    }

    // Loop through each sample
    for (iSmp = 0; iSmp < iNumSamples; iSmp++)
    {
        dComp     = 0;
        iMsecTime = cast(int)(1000 * iSmp / SAMPLE_RATE);

        // Loop through each partial
        for (iPrt = 0; iPrt < ins.pprt.length; iPrt++)
        {
            dAmp = 0;
            dFrq = 0;

            for (i = 0; i < ins.pprt[iPrt].ampArray.length - 1; i++)
            {
                if (iMsecTime >= ins.pprt[iPrt].ampArray[i].iTime &&
                    iMsecTime <= ins.pprt[iPrt].ampArray[i + 1].iTime)
                {
                    dFrac = cast(double)(iMsecTime -
                            ins.pprt[iPrt].ampArray[i].iTime) /
                            (ins.pprt[iPrt].ampArray[i + 1].iTime -
                             ins.pprt[iPrt].ampArray[i].iTime);

                    dAmp = dFrac * ins.pprt[iPrt].ampArray[i + 1].iValue +
                           (1 - dFrac) * ins.pprt[iPrt].ampArray[i].iValue;

                    break;
                }
            }

            for (i = 0; i < ins.pprt[iPrt].freqArray.length - 1; i++)
            {
                if (iMsecTime >= ins.pprt[iPrt].freqArray[i  ].iTime &&
                    iMsecTime <= ins.pprt[iPrt].freqArray[i + 1].iTime)
                {
                    dFrac = cast(double)(iMsecTime - ins.pprt[iPrt].freqArray[i  ].iTime) /
                            (ins.pprt[iPrt].freqArray[i + 1].iTime -
                             ins.pprt[iPrt].freqArray[i  ].iTime);

                    dFrq = dFrac * ins.pprt[iPrt].freqArray[i + 1].iValue +
                           (1 - dFrac) * ins.pprt[iPrt].freqArray[i  ].iValue;

                    break;
                }
            }

            dComp += dAmp * SineGenerator(dFrq, dAngle[iPrt]);
        }

        pBuffer[iSmp] = cast(BYTE)(127 + 127 * dComp / iCompMaxAmp);
    }
}

BOOL MakeWaveFile(INS ins, string szFileName)
{
    DWORD  dwWritten;
    HANDLE hFile;
    int iChunkSize, iPcmSize, iNumSamples;
    PBYTE pBuffer;
    WAVEFORMATEX waveform;

    hFile = CreateFile(szFileName.toUTF16z, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    enforce(hFile != NULL);

    iNumSamples = (cast(int)ins.iMsecTime * SAMPLE_RATE / 1000 + 1) / 2 * 2;
    iPcmSize    = PCMWAVEFORMAT.sizeof;
    iChunkSize  = 12 + iPcmSize + 8 + iNumSamples;

    pBuffer = cast(typeof(pBuffer))GC.malloc(iNumSamples);
    if (pBuffer is null)
    {
        CloseHandle(hFile);
        throw new Exception("Can't allocate buffer.");
    }

    FillBuffer(ins, pBuffer, iNumSamples);
    
    waveform.wFormatTag      = WAVE_FORMAT_PCM;
    waveform.nChannels       = 1;
    waveform.nSamplesPerSec  = SAMPLE_RATE;
    waveform.nAvgBytesPerSec = SAMPLE_RATE;
    waveform.nBlockAlign     = 1;
    waveform.wBitsPerSample  = 8;
    waveform.cbSize          = 0;

    // Note: WriteFile doesn't know anything about UTF8+, have to use ASCII
    // to write the file section names.
    string RIFF = "RIFF";
    string WAVEfmt = "WAVEfmt ";
    string DATA = "data";
    
    WriteFile(hFile, cast(void*)(RIFF.toStringz), 4, &dwWritten, NULL);
    WriteFile(hFile, &iChunkSize, 4, &dwWritten, NULL);
    WriteFile(hFile, cast(void*)(WAVEfmt.toStringz), 8, &dwWritten, NULL);
    WriteFile(hFile, &iPcmSize, 4, &dwWritten, NULL);
    WriteFile(hFile, &waveform, WAVEFORMATEX.sizeof - 2, &dwWritten, NULL);
    WriteFile(hFile, cast(void*)(DATA.toStringz), 4, &dwWritten, NULL);
    WriteFile(hFile, &iNumSamples, 4, &dwWritten, NULL);
    WriteFile(hFile, pBuffer, iNumSamples, &dwWritten, NULL);

    CloseHandle(hFile);
    GC.free(pBuffer);

    if (cast(int)dwWritten != iNumSamples)
    {
        DeleteFile(szFileName.toUTF16z);
        return FALSE;
    }

    return TRUE;
}

void TestAndCreateFile(HWND hwnd, INS ins, string szFileName, int idButton)
{
    if (GetFileAttributes(szFileName.toUTF16z) != -1)
        EnableWindow(GetDlgItem(hwnd, idButton), TRUE);
    else
    {
        if (MakeWaveFile(ins, szFileName))
            EnableWindow(GetDlgItem(hwnd, idButton), TRUE);
        else
        {
            string message = format("Could not create %s.", szFileName);
            MessageBeep(MB_ICONEXCLAMATION);
            MessageBox(hwnd, message.toUTF16z, appName.toUTF16z, MB_OK | MB_ICONEXCLAMATION);
        }
    }
}

extern (Windows)
BOOL DlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    string szTrum = "Trumpet.wav";
    string szOboe = "Oboe.wav";
    string szClar = "Clarinet.wav";

    switch (message)
    {
        case WM_INITDIALOG:
            SetTimer(hwnd, ID_TIMER, 1, NULL);
            return TRUE;

        case WM_TIMER:
            KillTimer(hwnd, ID_TIMER);
            SetCursor(LoadCursor(NULL, IDC_WAIT));
            ShowCursor(TRUE);

            TestAndCreateFile(hwnd, insTrum, szTrum, IDC_TRUMPET);
            TestAndCreateFile(hwnd, insOboe, szOboe, IDC_OBOE);
            TestAndCreateFile(hwnd, insClar, szClar, IDC_CLARINET);

            SetDlgItemText(hwnd, IDC_TEXT, " ");
            SetFocus(GetDlgItem(hwnd, IDC_TRUMPET));

            ShowCursor(FALSE);
            SetCursor(LoadCursor(NULL, IDC_ARROW));
            return TRUE;

        case WM_COMMAND:

            switch (LOWORD(wParam))
            {
                case IDC_TRUMPET:
                    PlaySound(szTrum.toUTF16z, NULL, SND_FILENAME | SND_SYNC);
                    return TRUE;

                case IDC_OBOE:
                    PlaySound(szOboe.toUTF16z, NULL, SND_FILENAME | SND_SYNC);
                    return TRUE;

                case IDC_CLARINET:
                    PlaySound(szClar.toUTF16z, NULL, SND_FILENAME | SND_SYNC);
                    return TRUE;
                
                default:
            }

            break;

        case WM_SYSCOMMAND:

            switch (LOWORD(wParam))
            {
                case SC_CLOSE:
                    EndDialog(hwnd, 0);
                    return TRUE;
                
                default:
            }

            break;
            
        default:
    }

    return FALSE;
}
Back to Top