-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLabSoundDemo.cpp
More file actions
1759 lines (1406 loc) · 64.1 KB
/
LabSoundDemo.cpp
File metadata and controls
1759 lines (1406 loc) · 64.1 KB
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: BSD-2-Clause
// Copyright (C) 2020, The LabSound Authors. All rights reserved.
#if defined(_MSC_VER)
#if !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#if !defined(NOMINMAX)
#define NOMINMAX
#endif
#endif
#define USE_LIVE
#include "LabSound/LabSound.h"
#include "LabSound/extended/Util.h"
#include "LabSoundDemo.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <functional>
#include <map>
#include <mutex>
#include <random>
#include <string>
#include <thread>
#include <vector>
#include <iostream>
#include <string>
// In the future, this class could do all kinds of clever things, like setting up the context,
// handling recording functionality, etc.
#include <string>
#include <vector>
using namespace lab;
#ifdef _MSC_VER
#include <windows.h>
std::string PrintCurrentDirectory()
{
char buffer[MAX_PATH] = {0};
GetCurrentDirectory(MAX_PATH, buffer);
return std::string(buffer);
}
#endif
struct labsound_example
{
std::mt19937 randomgenerator;
std::vector<std::shared_ptr<lab::AudioNode>> _nodes;
virtual void play(int argc, char** argv) = 0;
float MidiToFrequency(int midiNote)
{
return 440.0f * pow(2.0f, (midiNote - 57.0f) / 12.0f);
}
template <typename Duration>
void Wait(Duration duration)
{
std::this_thread::sleep_for(duration);
}
inline std::vector<std::string> SplitCommandLine(int argc, char ** argv)
{
// takes a string, and separates out according to embedded quoted strings
// the quotes are preserved, and quotes are escaped.
// examples
// * abc > abc
// * abc "def" > abc, "def"
// * a "def" ghi > a, "def", ghi
// * a\"bc > a\"bc
auto Separate = [](const std::string & input) -> std::vector<std::string>
{
std::vector<std::string> output;
size_t curr = 0;
size_t start = 0;
size_t end = input.length();
bool inQuotes = false;
while (curr < end)
{
if (input[curr] == '\\')
{
++curr;
if (curr != end && input[curr] == '\"')
++curr;
}
else
{
if (input[curr] == '\"')
{
// no empty string if not in quotes, otherwise preserve it
if (inQuotes || (start != curr))
{
output.push_back(input.substr(start - (inQuotes ? 1 : 0), curr - start + (inQuotes ? 2 : 0)));
}
inQuotes = !inQuotes;
start = curr + 1;
}
++curr;
}
}
// catch the case of a trailing substring that was not quoted, or a completely unquoted string
if (curr - start > 0) output.push_back(input.substr(start, curr - start));
return output;
};
// join the command line together so quoted strings can be found
std::string cmd;
for (int i = 1; i < argc; ++i)
{
if (i > 1) cmd += " ";
cmd += std::string(argv[i]);
}
// separate the command line, respecting quoted strings
std::vector<std::string> result = Separate(cmd);
result.insert(result.begin(), std::string{argv[0]});
return result;
}
inline std::shared_ptr<AudioBus> MakeBusFromSampleFile(char const*const name, int argc, char** argv)
{
std::string path_prefix;
auto cmds = SplitCommandLine(argc, argv);
if (cmds.size() > 1) path_prefix = cmds[1] + "/"; // cmds[0] is the path to the exe
else path_prefix = asset_base;
const std::string path = path_prefix + name;
std::shared_ptr<AudioBus> bus = MakeBusFromFile(path, false);
if (!bus) throw std::runtime_error("couldn't open " + path);
return bus;
}
};
/////////////////////////////////////
// Example Utility Functions //
/////////////////////////////////////
// Returns input, output
inline std::pair<AudioStreamConfig, AudioStreamConfig> GetDefaultAudioDeviceConfiguration(const bool with_input = false)
{
AudioStreamConfig inputConfig;
AudioStreamConfig outputConfig;
const std::vector<AudioDeviceInfo> audioDevices = lab::MakeAudioDeviceList();
const AudioDeviceIndex default_output_device = lab::GetDefaultOutputAudioDeviceIndex();
const AudioDeviceIndex default_input_device = lab::GetDefaultInputAudioDeviceIndex();
AudioDeviceInfo defaultOutputInfo, defaultInputInfo;
for (auto & info : audioDevices)
{
if (info.index == default_output_device.index) defaultOutputInfo = info;
else if (info.index == default_input_device.index) defaultInputInfo = info;
}
if (defaultOutputInfo.index != -1)
{
outputConfig.device_index = defaultOutputInfo.index;
outputConfig.desired_channels = std::min(uint32_t(2), defaultOutputInfo.num_output_channels);
outputConfig.desired_samplerate = defaultOutputInfo.nominal_samplerate;
}
if (with_input)
{
if (defaultInputInfo.index != -1)
{
inputConfig.device_index = defaultInputInfo.index;
inputConfig.desired_channels = std::min(uint32_t(1), defaultInputInfo.num_input_channels);
inputConfig.desired_samplerate = defaultInputInfo.nominal_samplerate;
}
else
{
throw std::invalid_argument("the default audio input device was requested but none were found");
}
}
return {inputConfig, outputConfig};
}
//-----------------//
// ex_simple //
//-----------------//
// demonstrate the use of an audio clip loaded from disk and a basic sine oscillator.
struct ex_simple : public labsound_example
{
virtual void play(int argc, char** argv) override final
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration();
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
auto musicClip = MakeBusFromSampleFile("samples/stereo-music-clip.wav", argc, argv);
if (!musicClip)
return;
std::shared_ptr<OscillatorNode> oscillator;
std::shared_ptr<SampledAudioNode> musicClipNode;
std::shared_ptr<GainNode> gain;
oscillator = std::make_shared<OscillatorNode>(ac);
gain = std::make_shared<GainNode>(ac);
gain->gain()->setValue(0.5f);
musicClipNode = std::make_shared<SampledAudioNode>(ac);
{
ContextRenderLock r(context.get(), "ex_simple");
musicClipNode->setBus(r, musicClip);
}
context->connect(context->device(), musicClipNode, 0, 0);
musicClipNode->schedule(0.0);
// osc -> gain -> destination
context->connect(gain, oscillator, 0, 0);
context->connect(context->device(), gain, 0, 0);
oscillator->frequency()->setValue(440.f);
oscillator->setType(OscillatorType::SINE);
oscillator->start(0.0f);
_nodes.push_back(oscillator);
_nodes.push_back(musicClipNode);
_nodes.push_back(gain);
Wait(std::chrono::seconds(6));
}
};
//------------------------//
// ex_test_resample //
//------------------------//
// demonstrate the use of an audio clip loaded from disk and a basic sine oscillator.
struct ex_test_resample : public labsound_example
{
virtual void play(int argc, char** argv) override final
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration();
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
auto musicClip = MakeBusFromSampleFile("samples/sin440-22050.wav", argc, argv);
if (!musicClip)
return;
std::shared_ptr<OscillatorNode> oscillator;
std::shared_ptr<SampledAudioNode> musicClipNode;
std::shared_ptr<GainNode> gain;
oscillator = std::make_shared<OscillatorNode>(ac);
gain = std::make_shared<GainNode>(ac);
gain->gain()->setValue(0.5f);
musicClipNode = std::make_shared<SampledAudioNode>(ac);
{
ContextRenderLock r(context.get(), "ex_test_resample");
musicClipNode->setBus(r, musicClip);
}
context->connect(context->device(), musicClipNode, 0, 0);
// osc -> gain -> destination
context->connect(gain, oscillator, 0, 0);
context->connect(context->device(), gain, 0, 0);
oscillator->frequency()->setValue(440.f);
oscillator->setType(OscillatorType::SINE);
_nodes.push_back(oscillator);
_nodes.push_back(musicClipNode);
_nodes.push_back(gain);
oscillator->start(0.0f);
Wait(std::chrono::seconds(1));
oscillator->stop(0.0f);
Wait(std::chrono::milliseconds(500));
musicClipNode->schedule(0.0);
Wait(std::chrono::milliseconds(500));
musicClipNode->detune()->setValue(1000.f);
Wait(std::chrono::milliseconds(500));
}
};
//-----------------//
// ex_osc_pop //
//-----------------//
// ex_osc_pop to test oscillator start/stop popping (it shouldn't pop).
struct ex_osc_pop : public labsound_example
{
virtual void play(int argc, char** argv) override final
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration();
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
std::shared_ptr<OscillatorNode> oscillator;
std::shared_ptr<RecorderNode> recorder;
std::shared_ptr<GainNode> gain;
{
oscillator = std::make_shared<OscillatorNode>(ac);
gain = std::make_shared<GainNode>(ac);
gain->gain()->setValue(1);
// osc -> destination
context->connect(gain, oscillator, 0, 0);
context->connect(context->device(), gain, 0, 0);
oscillator->frequency()->setValue(1000.f);
oscillator->setType(OscillatorType::SINE);
recorder = std::make_shared<RecorderNode>(ac, defaultAudioDeviceConfigurations.second);
context->addAutomaticPullNode(recorder);
recorder->startRecording();
context->connect(recorder, gain, 0, 0);
}
// retain nodes until demo end
_nodes.push_back(oscillator);
_nodes.push_back(recorder);
_nodes.push_back(gain);
// queue up 5 1/2 second chirps
for (float i = 0; i < 5.f; i += 1.f)
{
oscillator->start(0);
oscillator->stop(0.5f);
Wait(std::chrono::milliseconds(1000));
}
recorder->stopRecording();
context->removeAutomaticPullNode(recorder);
recorder->writeRecordingToWav("ex_osc_pop.wav", false);
// wait at least one context update to allow the disconnections to occur, and for any final
// render quantum to finish.
// @TODO the only safe and reasonable thing is to expose a "join" on the context that
// disconnects the destination node from its graph, then waits a quantum.
// @TODO the example app should have a set<shared_ptr<AudioNode>> so that the shared_ptrs
// are not released until the example is finished.
context->disconnect(context->device());
Wait(std::chrono::milliseconds(100));
}
};
//////////////////////////////
// ex_playback_events //
//////////////////////////////
// ex_playback_events showcases the use of a `setOnEnded` callback on a `SampledAudioNode`
struct ex_playback_events : public labsound_example
{
virtual void play(int argc, char ** argv) override
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration();
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
auto musicClip = MakeBusFromSampleFile("samples/mono-music-clip.wav", argc, argv);
if (!musicClip)
return;
auto sampledAudio = std::make_shared<SampledAudioNode>(ac);
{
ContextRenderLock r(context.get(), "ex_playback_events");
sampledAudio->setBus(r, musicClip);
}
context->connect(context->device(), sampledAudio, 0, 0);
sampledAudio->setOnEnded([]() {
std::cout << "sampledAudio finished..." << std::endl;
});
sampledAudio->schedule(0.0);
Wait(std::chrono::seconds(6));
}
};
////////////////////////////////
// ex_offline_rendering //
////////////////////////////////
// This sample illustrates how LabSound can be used "offline," where the graph is not
// pulled by an actual audio device, but rather a null destination. This sample shows
// how a `RecorderNode` can be used to capture the rendered audio to disk.
struct ex_offline_rendering : public labsound_example
{
virtual void play(int argc, char ** argv) override
{
AudioStreamConfig offlineConfig;
offlineConfig.device_index = 0;
offlineConfig.desired_samplerate = LABSOUND_DEFAULT_SAMPLERATE;
offlineConfig.desired_channels = LABSOUND_DEFAULT_CHANNELS;
const float recording_time_ms = 1000.f;
std::unique_ptr<lab::AudioContext> context = lab::MakeOfflineAudioContext(offlineConfig, recording_time_ms);
lab::AudioContext& ac = *context.get();
std::shared_ptr<OscillatorNode> oscillator;
std::shared_ptr<AudioBus> musicClip = MakeBusFromSampleFile("samples/stereo-music-clip.wav", argc, argv);
std::shared_ptr<SampledAudioNode> musicClipNode;
std::shared_ptr<GainNode> gain;
auto recorder = std::make_shared<RecorderNode>(ac, offlineConfig);
context->addAutomaticPullNode(recorder);
recorder->startRecording();
{
ContextRenderLock r(context.get(), "ex_offline_rendering");
gain = std::make_shared<GainNode>(ac);
gain->gain()->setValue(0.125f);
// osc -> gain -> recorder
oscillator = std::make_shared<OscillatorNode>(ac);
context->connect(gain, oscillator, 0, 0);
context->connect(recorder, gain, 0, 0);
oscillator->frequency()->setValue(880.f);
oscillator->setType(OscillatorType::SINE);
oscillator->start(0.0f);
musicClipNode = std::make_shared<SampledAudioNode>(ac);
context->connect(recorder, musicClipNode, 0, 0);
musicClipNode->setBus(r, musicClip);
musicClipNode->schedule(0.0);
}
bool complete = false;
context->offlineRenderCompleteCallback = [&context, &recorder, &complete]() {
recorder->stopRecording();
printf("Recorded %f seconds of audio\n", recorder->recordedLengthInSeconds());
context->removeAutomaticPullNode(recorder);
recorder->writeRecordingToWav("ex_offline_rendering.wav", false);
complete = true;
};
// Offline rendering happens in a separate thread and blocks until complete.
// It needs to acquire the graph + render locks, so it must
// be outside the scope of where we make changes to the graph.
context->startOfflineRendering();
while (!complete)
{
Wait(std::chrono::milliseconds(100));
}
}
};
//////////////////////
// ex_tremolo //
//////////////////////
// This demonstrates the use of `connectParam` as a way of modulating one node through another.
// Params are effectively control signals that operate at audio rate.
struct ex_tremolo : public labsound_example
{
virtual void play(int argc, char ** argv) override
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration();
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
std::shared_ptr<OscillatorNode> modulator;
std::shared_ptr<GainNode> modulatorGain;
std::shared_ptr<OscillatorNode> osc;
{
modulator = std::make_shared<OscillatorNode>(ac);
modulator->setType(OscillatorType::SINE);
modulator->frequency()->setValue(8.0f);
modulator->start(0);
modulatorGain = std::make_shared<GainNode>(ac);
modulatorGain->gain()->setValue(10);
osc = std::make_shared<OscillatorNode>(ac);
osc->setType(OscillatorType::TRIANGLE);
osc->frequency()->setValue(440);
osc->start(0);
// Set up processing chain
// modulator > modulatorGain ---> osc frequency
// osc > context
context->connect(modulatorGain, modulator, 0, 0);
context->connectParam(osc->detune(), modulatorGain, 0);
context->connect(context->device(), osc, 0, 0);
}
Wait(std::chrono::seconds(5));
}
};
///////////////////////////////////
// ex_frequency_modulation //
///////////////////////////////////
// This is inspired by a patch created in the ChucK audio programming language. It showcases
// LabSound's ability to construct arbitrary graphs of oscillators a-la FM synthesis.
struct ex_frequency_modulation : public labsound_example
{
virtual void play(int argc, char ** argv) override
{
UniformRandomGenerator fmrng;
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration();
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
std::shared_ptr<OscillatorNode> modulator;
std::shared_ptr<GainNode> modulatorGain;
std::shared_ptr<OscillatorNode> osc;
std::shared_ptr<ADSRNode> trigger;
std::shared_ptr<GainNode> signalGain;
std::shared_ptr<GainNode> feedbackTap;
std::shared_ptr<DelayNode> chainDelay;
{
modulator = std::make_shared<OscillatorNode>(ac);
modulator->setType(OscillatorType::SQUARE);
modulator->start(0);
modulatorGain = std::make_shared<GainNode>(ac);
osc = std::make_shared<OscillatorNode>(ac);
osc->setType(OscillatorType::SQUARE);
osc->frequency()->setValue(300);
osc->start(0);
trigger = std::make_shared<ADSRNode>(ac);
signalGain = std::make_shared<GainNode>(ac);
signalGain->gain()->setValue(1.0f);
feedbackTap = std::make_shared<GainNode>(ac);
feedbackTap->gain()->setValue(0.5f);
chainDelay = std::make_shared<DelayNode>(ac, 4);
chainDelay->delayTime()->setFloat(0.0f); // passthrough delay, not sure if this has the same DSP semantic as ChucK
// Set up FM processing chain:
context->connect(modulatorGain, modulator, 0, 0); // Modulator to Gain
context->connectParam(osc->frequency(), modulatorGain, 0); // Gain to frequency parameter
context->connect(trigger, osc, 0, 0); // Osc to ADSR
context->connect(signalGain, trigger, 0, 0); // ADSR to signalGain
context->connect(feedbackTap, signalGain, 0, 0); // Signal to Feedback
context->connect(chainDelay, feedbackTap, 0, 0); // Feedback to Delay
context->connect(signalGain, chainDelay, 0, 0); // Delay to signalGain
context->connect(context->device(), signalGain, 0, 0); // signalGain to DAC
}
double now_in_ms = 0;
while (true)
{
const float carrier_freq = fmrng.random_float(80.f, 440.f);
osc->frequency()->setValue(carrier_freq);
const float mod_freq = fmrng.random_float(4.f, 512.f);
modulator->frequency()->setValue(mod_freq);
const float mod_gain = fmrng.random_float(16.f, 1024.f);
modulatorGain->gain()->setValue(mod_gain);
const float attack_length = fmrng.random_float(0.25f, 0.5f);
trigger->set(attack_length, 0.50f, 0.50f, 0.25f, 0.50f, 0.1f);
trigger->gate()->setValue(1.f);
const uint32_t delay_time_ms = 500;
now_in_ms += delay_time_ms;
std::cout << "[ex_frequency_modulation] car_freq: " << carrier_freq << std::endl;
std::cout << "[ex_frequency_modulation] mod_freq: " << mod_freq << std::endl;
std::cout << "[ex_frequency_modulation] mod_gain: " << mod_gain << std::endl;
Wait(std::chrono::milliseconds(delay_time_ms));
if (now_in_ms >= 10000) break;
};
}
};
///////////////////////////////////
// ex_runtime_graph_update //
///////////////////////////////////
// In most examples, nodes are not disconnected during playback. This sample shows how nodes
// can be arbitrarily connected/disconnected during runtime while the graph is live.
struct ex_runtime_graph_update : public labsound_example
{
virtual void play(int argc, char ** argv) override
{
std::shared_ptr<OscillatorNode> oscillator1, oscillator2;
std::shared_ptr<GainNode> gain;
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration();
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
{
oscillator1 = std::make_shared<OscillatorNode>(ac);
oscillator2 = std::make_shared<OscillatorNode>(ac);
gain = std::make_shared<GainNode>(ac);
gain->gain()->setValue(0.50);
// osc -> gain -> destination
context->connect(gain, oscillator1, 0, 0);
context->connect(gain, oscillator2, 0, 0);
context->connect(context->device(), gain, 0, 0);
oscillator1->setType(OscillatorType::SINE);
oscillator1->frequency()->setValue(220.f);
oscillator1->start(0.00f);
oscillator2->setType(OscillatorType::SINE);
oscillator2->frequency()->setValue(440.f);
oscillator2->start(0.00);
}
_nodes.push_back(oscillator1);
_nodes.push_back(oscillator2);
_nodes.push_back(gain);
for (int i = 0; i < 4; ++i)
{
context->disconnect(nullptr, oscillator1, 0, 0);
context->connect(gain, oscillator2, 0, 0);
Wait(std::chrono::milliseconds(200));
context->disconnect(nullptr, oscillator2, 0, 0);
context->connect(gain, oscillator1, 0, 0);
Wait(std::chrono::milliseconds(200));
}
context->disconnect(nullptr, oscillator1, 0, 0);
context->disconnect(nullptr, oscillator2, 0, 0);
}
std::cout << "OscillatorNode 1 use_count: " << oscillator1.use_count() << std::endl;
std::cout << "OscillatorNode 2 use_count: " << oscillator2.use_count() << std::endl;
std::cout << "GainNode use_count: " << gain.use_count() << std::endl;
}
};
//////////////////////////////////
// ex_microphone_loopback //
//////////////////////////////////
// This example simply connects an input device (e.g. a microphone) to the output audio device (e.g. your speakers).
// DANGER! This sample creates an open feedback loop. It is best used when the output audio device is a pair of headphones.
struct ex_microphone_loopback : public labsound_example
{
virtual void play(int argc, char ** argv) override
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration(true);
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
std::shared_ptr<AudioHardwareInputNode> input;
{
ContextRenderLock r(context.get(), "ex_microphone_loopback");
input = lab::MakeAudioHardwareInputNode(r);
context->connect(context->device(), input, 0, 0);
}
Wait(std::chrono::seconds(10));
}
};
////////////////////////////////
// ex_microphone_reverb //
////////////////////////////////
// This sample takes input from a microphone and convolves it with an impulse response to create reverb (i.e. use of the `ConvolverNode`).
// The sample convolution is for a rather large room, so there is a delay.
// DANGER! This sample creates an open feedback loop. It is best used when the output audio device is a pair of headphones.
struct ex_microphone_reverb : public labsound_example
{
virtual void play(int argc, char ** argv) override
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration(true);
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
{
std::shared_ptr<AudioBus> impulseResponseClip = MakeBusFromFile("impulse/cardiod-rear-levelled.wav", false);
std::shared_ptr<AudioHardwareInputNode> input;
std::shared_ptr<ConvolverNode> convolve;
std::shared_ptr<GainNode> wetGain;
std::shared_ptr<RecorderNode> recorder;
{
ContextRenderLock r(context.get(), "ex_microphone_reverb");
input = lab::MakeAudioHardwareInputNode(r);
recorder = std::make_shared<RecorderNode>(ac, defaultAudioDeviceConfigurations.second);
context->addAutomaticPullNode(recorder);
recorder->startRecording();
convolve = std::make_shared<ConvolverNode>(ac);
convolve->setImpulse(impulseResponseClip);
wetGain = std::make_shared<GainNode>(ac);
wetGain->gain()->setValue(0.6f);
context->connect(convolve, input, 0, 0);
context->connect(wetGain, convolve, 0, 0);
context->connect(context->device(), wetGain, 0, 0);
context->connect(recorder, wetGain, 0, 0);
}
Wait(std::chrono::seconds(10));
recorder->stopRecording();
context->removeAutomaticPullNode(recorder);
recorder->writeRecordingToWav("ex_microphone_reverb.wav", true);
context.reset();
}
}
};
//////////////////////////////
// ex_peak_compressor //
//////////////////////////////
// Demonstrates the use of the `PeakCompNode` and many scheduled audio sources.
struct ex_peak_compressor : public labsound_example
{
virtual void play(int argc, char ** argv) override
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration();
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
std::shared_ptr<AudioBus> kick = MakeBusFromSampleFile("samples/kick.wav", argc, argv);
std::shared_ptr<AudioBus> hihat = MakeBusFromSampleFile("samples/hihat.wav", argc, argv);
std::shared_ptr<AudioBus> snare = MakeBusFromSampleFile("samples/snare.wav", argc, argv);
std::shared_ptr<SampledAudioNode> kick_node = std::make_shared<SampledAudioNode>(ac);
std::shared_ptr<SampledAudioNode> hihat_node = std::make_shared<SampledAudioNode>(ac);
std::shared_ptr<SampledAudioNode> snare_node = std::make_shared<SampledAudioNode>(ac);
std::shared_ptr<BiquadFilterNode> filter;
std::shared_ptr<PeakCompNode> peakComp;
{
ContextRenderLock r(context.get(), "ex_peak_compressor");
filter = std::make_shared<BiquadFilterNode>(ac);
filter->setType(lab::FilterType::LOWPASS);
filter->frequency()->setValue(1800.f);
peakComp = std::make_shared<PeakCompNode>(ac);
context->connect(peakComp, filter, 0, 0);
context->connect(context->device(), peakComp, 0, 0);
kick_node->setBus(r, kick);
context->connect(filter, kick_node, 0, 0);
hihat_node->setBus(r, hihat);
context->connect(filter, hihat_node, 0, 0);
//hihat_node->gain()->setValue(0.2f);
snare_node->setBus(r, snare);
context->connect(filter, snare_node, 0, 0);
_nodes.push_back(kick_node);
_nodes.push_back(hihat_node);
_nodes.push_back(snare_node);
_nodes.push_back(peakComp);
_nodes.push_back(filter);
}
// Speed Metal
float startTime = 0.1f;
float bpm = 30.f;
float bar_length = 60.f / bpm;
float eighthNoteTime = bar_length / 8.0f;
for (float bar = 0; bar < 8; bar += 1)
{
float time = startTime + bar * bar_length;
kick_node->schedule(time);
kick_node->schedule(time + 4 * eighthNoteTime);
snare_node->schedule(time + 2 * eighthNoteTime);
snare_node->schedule(time + 6 * eighthNoteTime);
float hihat_beat = 8;
for (float i = 0; i < hihat_beat; i += 1)
hihat_node->schedule(time + bar_length * i / hihat_beat);
}
Wait(std::chrono::seconds(10));
}
};
/////////////////////////////
// ex_stereo_panning //
/////////////////////////////
// This illustrates the use of equal-power stereo panning.
struct ex_stereo_panning : public labsound_example
{
virtual void play(int argc, char ** argv) override
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration();
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
std::shared_ptr<AudioBus> audioClip = MakeBusFromSampleFile("samples/trainrolling.wav", argc, argv);
std::shared_ptr<SampledAudioNode> audioClipNode = std::make_shared<SampledAudioNode>(ac);
auto stereoPanner = std::make_shared<StereoPannerNode>(ac);
{
ContextRenderLock r(context.get(), "ex_stereo_panning");
audioClipNode->setBus(r, audioClip);
context->connect(stereoPanner, audioClipNode, 0, 0);
audioClipNode->schedule(0.0, -1); // -1 to loop forever
context->connect(context->device(), stereoPanner, 0, 0);
}
if (audioClipNode)
{
_nodes.push_back(audioClipNode);
_nodes.push_back(stereoPanner);
const int seconds = 8;
std::thread controlThreadTest([&stereoPanner, seconds]() {
float halfTime = seconds * 0.5f;
for (float i = 0; i < seconds; i += 0.01f)
{
float x = (i - halfTime) / halfTime;
stereoPanner->pan()->setValue(x);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
});
Wait(std::chrono::seconds(seconds));
controlThreadTest.join();
}
else
{
std::cerr << "Couldn't initialize train node to play" << std::endl;
}
}
};
//////////////////////////////////
// ex_hrtf_spatialization //
//////////////////////////////////
// This illustrates 3d sound spatialization and doppler shift. Headphones are recommended for this sample.
struct ex_hrtf_spatialization : public labsound_example
{
virtual void play(int argc, char ** argv) override
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration();
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
std::shared_ptr<AudioBus> audioClip = MakeBusFromSampleFile("samples/trainrolling.wav", argc, argv);
std::shared_ptr<SampledAudioNode> audioClipNode = std::make_shared<SampledAudioNode>(ac);
std::cout << "Sample Rate is: " << context->sampleRate() << std::endl;
std::shared_ptr<PannerNode> panner = std::make_shared<PannerNode>(ac, "hrtf"); // note hrtf search path
{
ContextRenderLock r(context.get(), "ex_hrtf_spatialization");
panner->setPanningModel(PanningMode::HRTF);
context->connect(context->device(), panner, 0, 0);
audioClipNode->setBus(r, audioClip);
context->connect(panner, audioClipNode, 0, 0);
audioClipNode->schedule(0.0, -1); // -1 to loop forever
}
if (audioClipNode)
{
_nodes.push_back(audioClipNode);
_nodes.push_back(panner);
context->listener()->setPosition({0, 0, 0});
panner->setVelocity(4, 0, 0);
const int seconds = 10;
float halfTime = seconds * 0.5f;
for (float i = 0; i < seconds; i += 0.01f)
{
float x = (i - halfTime) / halfTime;
// Put position a +up && +front, because if it goes right through the
// listener at (0, 0, 0) it abruptly switches from left to right.
panner->setPosition({x, 0.1f, 0.1f});
Wait(std::chrono::milliseconds(10));
}
}
else
{
std::cerr << "Couldn't initialize train node to play" << std::endl;
}
}
};
////////////////////////////////
// ex_convolution_reverb //
////////////////////////////////
// This shows the use of the `ConvolverNode` to produce reverb from an arbitrary impulse response.
struct ex_convolution_reverb : public labsound_example
{
virtual void play(int argc, char ** argv) override
{
std::unique_ptr<lab::AudioContext> context;
const auto defaultAudioDeviceConfigurations = GetDefaultAudioDeviceConfiguration();
context = lab::MakeRealtimeAudioContext(defaultAudioDeviceConfigurations.second, defaultAudioDeviceConfigurations.first);
lab::AudioContext& ac = *context.get();
std::shared_ptr<AudioBus> impulseResponseClip = MakeBusFromFile("impulse/cardiod-rear-levelled.wav", false);
std::shared_ptr<AudioBus> voiceClip = MakeBusFromFile("samples/voice.ogg", false);
if (!impulseResponseClip || !voiceClip)
{
std::cerr << "Could not open sample data\n";
return;
}
std::shared_ptr<ConvolverNode> convolve;
std::shared_ptr<GainNode> wetGain;
std::shared_ptr<GainNode> dryGain;
std::shared_ptr<SampledAudioNode> voiceNode;
std::shared_ptr<GainNode> outputGain = std::make_shared<GainNode>(ac);
{
// voice --+-> dry -------------------+
// | |
// +---> convolve ---> wet ---+--->out ---> device
ContextRenderLock r(context.get(), "ex_convolution_reverb");
convolve = std::make_shared<ConvolverNode>(ac);
convolve->setImpulse(impulseResponseClip);
wetGain = std::make_shared<GainNode>(ac);
wetGain->gain()->setValue(0.5f);
dryGain = std::make_shared<GainNode>(ac);
dryGain->gain()->setValue(0.1f);
context->connect(wetGain, convolve, 0, 0);
context->connect(outputGain, wetGain, 0, 0);
context->connect(outputGain, dryGain, 0, 0);
context->connect(convolve, dryGain, 0, 0);