-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSound.cpp
1617 lines (1487 loc) · 53.4 KB
/
Sound.cpp
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
/** Copyright (C) 2016, Florin Oprea <florinoprea.contact@gmail.com>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License along
** with this program; if not, write to the Free Software Foundation, Inc.,
** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**/
#include "Sound.h"
#include <QDebug>
Sound::Sound(QObject *parent) :
QObject(parent)
{
type = SOUNDTYPE_EMPTY;
soundState = 0;
soundStateExpected = 0;
//We need soundStateExpected because media sounds that are resumed are a bit lazy to
//update state to QMediaPlayer::PlayingState
//And if we call wait() just after pause()/play() we can have a chance to miss the waiting
//Sequence: play(), pause(), play()/resume, wait()
//A solution was to wait after each play() or pause() by loosing speed
byteArray = NULL;
buffer = NULL;
audio = NULL;
media = NULL;
source = "";
isStopping = false;
needValidation = true;
isValidated = false;
individualVolume = 1.0;
media_duration = -1; //used only by mediaplayer because duration may not be available when initial playback begins
masterVolume = 10;
scheduledFade = false;
fadeVolume = 1.0;
fadeCountdown = 0;
fadeDelayCountdown = 0;
loopCountdown = 1; //play only once
loopSaved = 1; //play only once
isPositionChanged = true; //first position is 0
isReady = false;
error = NULL;
isPausedBySystem = false;
}
Sound::~Sound() {
if(audio){
while(audio->state()!=QAudio::StoppedState) audio->stop();
delete(audio);
audio=NULL;
}
if(media){
delete(media);
media=NULL;
}
if(buffer){
buffer->close();
delete(buffer);
buffer=NULL;
}
delete(byteArray);
byteArray=NULL;
}
int Sound::state() {
return soundState;
}
void Sound::play() {
if(!isStopping){
if(audio){
if(soundStateExpected == 2){
soundStateExpected = 1;
audio->resume();
isPausedBySystem = false;
if(scheduledFade){
scheduledFade=false;
fadeTimer.start(SOUNDFADEMS, this);
}
}else if(soundStateExpected == 0){
soundStateExpected = 1;
audio->start(buffer);
isPausedBySystem = false;
if(scheduledFade){
scheduledFade=false;
fadeTimer.start(SOUNDFADEMS, this);
}
}
if(audio->error()!=QAudio::NoError && audio->error()!=QAudio::UnderrunError){
isStopping=true;
if(*error)(*error)->q(WARNING_SOUNDERROR);
audio->disconnect(this);
emit(deleteMe(id));
this->disconnect();
return;
}
}else if(media){
if(needValidation){
isValidated=waitLoadedMediaValidation();
//qDebug() << "isValidated" << isValidated;
needValidation=false;
emit(validateLoadedSound(source, isValidated));
}
if(!isValidated){
if(type == SOUNDTYPE_MEMORY){
if(*error)(*error)->q(WARNING_SOUNDERROR);
}else{
if(*error)(*error)->q(WARNING_SOUNDFILEFORMAT);
}
return;
}
if(soundStateExpected != 1){
isPausedBySystem = false;
if(media_duration>0 && media_duration==media->position() && soundStateExpected != 0){
//this is needed because QMediaPlayer has a bug
//When user send a huge amount of play/pause/play/pause commands to a QMediaPlayer, then sound do not
//emit QMediaPlayer::StoppedState or QMediaPlayer::EndOfMedia when reach the end because of stack
//of commands. So we can not detect when sound is finished.
//In this situation QMediaPlayer remain in QMediaPlayer::PlayingState like forever.
//This is a trick to detect if QMediaPlayer reach the end of sound and stop it.
//soundStateExpected = 0;
media->stop();
}else{
soundStateExpected = 1;
media->play();
if(scheduledFade){
scheduledFade=false;
fadeTimer.start(SOUNDFADEMS, this);
}
}
}
}
}
}
void Sound::stop() {
if(!isPlayer) isStopping = true;
soundStateExpected = 0;
loopCountdown=1; //this is the last loop
if(audio){
audio->stop();
isPausedBySystem = false;
}else if(media){
media->stop();
isPausedBySystem = false;
}
}
void Sound::pause() {
if(soundStateExpected==1 && !isStopping){
if(audio){
soundStateExpected = 2;
audio->suspend();
isPausedBySystem = false;
}else if(media){
if(isValidated){
soundStateExpected = 2;
media->pause();
isPausedBySystem = false;
}
}
}
}
void Sound::wait() {
//Wait till the end of sound or till the end of program
if(soundStateExpected==1){
QEventLoop *loop = new QEventLoop();
QObject::connect(this, SIGNAL(exitWaitingLoop()), loop, SLOT(quit()));
if(audio){
QObject::connect(audio, SIGNAL(stateChanged(QAudio::State)), loop, SLOT(quit()));
while(!isStopping && audio && audio->state() == QAudio::ActiveState){
loop->exec(QEventLoop::WaitForMoreEvents);
}
}else if(media){
QObject::connect(media, SIGNAL(stateChanged(QMediaPlayer::State)), loop, SLOT(quit()));
while(!isStopping && media && (media->state() == QMediaPlayer::PlayingState || (media->state() == QMediaPlayer::PausedState && soundStateExpected==1))){
loop->exec(QEventLoop::WaitForMoreEvents);
}
}
delete (loop);
}
}
bool Sound::waitLoadedMediaValidation() {
//this function waits a bit after play command to check if buffer contain a valid media file
//because QMediaPlayer::play remains in Play state when a fake sound is loaded into memory and played
//The only trick I found is that when first mediaStatusChanged is emitted, the duration is 0 for fake media
//http://stackoverflow.com/questions/42168280/qmediaplayer-play-a-sound-loaded-into-memory
//PS This validation should be fired only once, at first play
QTimer *timer = new QTimer();
timer->setSingleShot(true);
QEventLoop *loop = new QEventLoop();
QObject::connect(this, SIGNAL(exitWaitingLoop()), loop, SLOT(quit()));
QObject::connect(timer, SIGNAL(timeout()), loop, SLOT(quit()));
timer->start(3000);
//QObject::connect(media, SIGNAL(stateChanged(QMediaPlayer::State)), loop, SLOT(quit()));
QObject::connect(media, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), loop, SLOT(quit()));
QObject::connect(media, SIGNAL(durationChanged(qint64)), loop, SLOT(quit()));
if(!isStopping){
loop->exec(QEventLoop::ExcludeUserInputEvents);
}
//qDebug() << "Sound::waitLoadedMediaValidation() timer" << timer->isActive();
delete (loop);
delete (timer);
return (media_duration>0);
}
double Sound::position() {
//Return the position of the played sound
//Attention: elapsedUSecs returns the microseconds since start() was called, including time
//in Idle and Suspend states. So, in this case, we gonna use buffer->pos() instead.
if(audio){
if(buffer){
return ((double)buffer->pos() / ((double)sound_samplerate * (double) sizeof(int16_t)));
}
}else if(media){
//for media files, we ensure that last seek command is finished
waitLastMediaSeekTakeAction();
return media->position() / (double)(1000.0);
}
return 0.0;
}
bool Sound::seek(double sec) {
//For QAudio the seeking must be done by using the buffer. Attention: the new position must be divisible
//with sizeof(int16_t) - the sample size of generated sound is 16 bit
//For QMediaPlayer we need to wait a bit if the sound is not seekable for the moment, but not loger than 2 seconds
if(audio){
return (buffer->seek( (qint64)((double)sound_samplerate * sec) * (qint64) sizeof(int16_t)));
}else if(media){
if(!isReady) waitMediaStatusChanged();
waitLastMediaSeekTakeAction();
if(!isStopping){
if(media->isSeekable()) {
isPositionChanged = false;
media->setPosition(sec * 1000L);
return true;
} else {
QTimer *timer = new QTimer();
timer->setSingleShot(true);
QEventLoop *loop = new QEventLoop();
connect(timer, SIGNAL(timeout()), loop, SLOT(quit()));
timer->start(2000);
QObject::connect(this, SIGNAL(exitWaitingLoop()), loop, SLOT(quit()));
QObject::connect(media, SIGNAL(stateChanged(QMediaPlayer::State)), loop, SLOT(quit()));
QObject::connect(media, SIGNAL(seekableChanged(bool)), loop, SLOT(quit()));
while(!isStopping && media && !media->isSeekable() && media->state() != QMediaPlayer::StoppedState && timer->isActive()){
loop->exec(QEventLoop::WaitForMoreEvents);
}
delete (loop);
delete (timer);
if(media->isSeekable()) {
isPositionChanged = false;
media->setPosition(sec * 1000L);
return true;
} else {
return false;
}
}
}
}
return true;
}
void Sound::waitLastMediaSeekTakeAction(){
//If we seek into a media file multiple times, only the first seek command take action
//We need to wait for SIGNAL QMediaPlayer::positionChanged(qint64 position)
//to make sure that previous seek command is processed.
//Only then we can set another position or read the current position after a seek.
//A simple solution is to wait after each seek command, but thus we lose speed.
if(!isPositionChanged && !isStopping){
//wait for the last seek command to take action
QTimer *timer = new QTimer();
timer->setSingleShot(true);
QEventLoop *loop = new QEventLoop();
connect(timer, SIGNAL(timeout()), loop, SLOT(quit()));
timer->start(2000);
QObject::connect(this, SIGNAL(exitWaitingLoop()), loop, SLOT(quit()));
QObject::connect(media, SIGNAL(stateChanged(QMediaPlayer::State)), loop, SLOT(quit()));
QObject::connect(media, SIGNAL(positionChanged(qint64)), loop, SLOT(quit()));
while(!isStopping && !isPositionChanged && timer->isActive()){
loop->exec(QEventLoop::WaitForMoreEvents);
}
delete (loop);
delete (timer);
}
}
void Sound::waitMediaStatusChanged(){
//If we seek into a media file multiple times, only the first seek command take action
//We need to wait for SIGNAL QMediaPlayer::positionChanged(qint64 position)
//to make sure that previous seek command is processed.
//Only then we can set another position or read the current position after a seek.
//A simple solution is to wait after each seek command, but thus we lose speed.
if(!isReady && !isStopping){
//wait for the last seek command to take action
QTimer *timer = new QTimer();
timer->setSingleShot(true);
QEventLoop *loop = new QEventLoop();
connect(timer, SIGNAL(timeout()), loop, SLOT(quit()));
timer->start(2000);
QObject::connect(this, SIGNAL(exitWaitingLoop()), loop, SLOT(quit()));
QObject::connect(media, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), loop, SLOT(quit()));
if(!isStopping){
loop->exec(QEventLoop::WaitForMoreEvents);
}
delete (loop);
delete (timer);
}
}
double Sound::length() {
//For QMediaPlayer the length of played sound may not be available when initial playback begins (asyncron mode).
//If we need the length for a media we may wait a bit right after sound starts to play, but not longer than 2 seconds.
if(audio){
return ( buffer->size() / (double) sizeof(int16_t) / (double)sound_samplerate );
}else if(media){
bool timeisup = false;
if(media_duration<0.0){
QTimer *timer = new QTimer();
timer->setSingleShot(true);
QEventLoop *loop = new QEventLoop();
connect(timer, SIGNAL(timeout()), loop, SLOT(quit()));
timer->start(2000);
QObject::connect(this, SIGNAL(exitWaitingLoop()), loop, SLOT(quit()));
QObject::connect(media, SIGNAL(stateChanged(QMediaPlayer::State)), loop, SLOT(quit()));
QObject::connect(media, SIGNAL(durationChanged(qint64)), loop, SLOT(quit()));
while(!isStopping && timer->isActive() && media_duration<0.0){
loop->exec(QEventLoop::WaitForMoreEvents);
}
if(!timer->isActive()) timeisup=true;
delete (loop);
delete (timer);
}
if(timeisup || media_duration<0.0) return (-1.0); //return -1 to display a warning
return (media_duration/1000.0);
}
return 0;
}
//tell that the master volume has been changed
void Sound::updatedMasterVolume(double v) {
masterVolume=v; //keep value for fade effect
if(audio){
audio->setVolume((qreal)(v/10.0*individualVolume));
}else if(media){
media->setVolume(v*10.0*individualVolume);
}
}
int Sound::lastError() {
if(audio){
return audio->error();
}else if(media){
return media->error();
}
return 0;
}
void Sound::prepareConnections() {
if(audio){
connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleAudioStateChanged(QAudio::State)));
}else if(media){
connect(media, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), this, SLOT(handleMediaStatusChanged(QMediaPlayer::MediaStatus)));
connect(media, SIGNAL(stateChanged(QMediaPlayer::State)), this, SLOT(handleMediaStateChanged(QMediaPlayer::State)));
connect(media, SIGNAL(durationChanged(qint64)), this, SLOT(handleMediaDurationChanged(qint64)));
connect(media, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(handleMediaError(QMediaPlayer::Error)));
connect(media, SIGNAL(positionChanged(qint64)), this, SLOT(handlePositionChanged(qint64)));
}
}
void Sound::handlePositionChanged(qint64 position){
//Signal the position of the content has changed to position, expressed in milliseconds.
isPositionChanged = true;
//This flag is usefull because we need to wait before make another seek
//or before return the true position after a seek action
}
void Sound::handleMediaStatusChanged(QMediaPlayer::MediaStatus s){
if(s!=QMediaPlayer::LoadingMedia){
isReady = true;
if(needValidation){ //media is nor loaded yet
isValidated=false;
needValidation=false;
}
}
}
void Sound::handleMediaDurationChanged(qint64 d){
media_duration=d;
if(needValidation){
isValidated=media->duration()>0.0;
needValidation=false;
}
}
void Sound::handleMediaError(QMediaPlayer::Error err) {
if(needValidation){
isValidated=media->duration()>0.0;
needValidation=false;
}
//qDebug() << err;
}
void Sound::handleMediaStateChanged(QMediaPlayer::State newState){
soundState = newState;
if(newState==QMediaPlayer::StoppedState){
soundStateExpected=0;
if(loopCountdown==1 || isStopping){ //if this was the last loop or the user request to stop
if(fadeTimer.isActive()) fadeTimer.stop();
if(!isPlayer){
isStopping=true;
media->disconnect(this);
emit(exitWaitingLoop());
media->setMedia(QMediaContent());
emit(deleteMe(id));
this->disconnect();
}else{
loopCountdown=loopSaved; //Recharge number of loops
media->setPosition(0);
}
}else{
if(loopCountdown>1) loopCountdown--;
play();
}
}
}
void Sound::handleAudioStateChanged(QAudio::State newState){
switch (newState) {
case QAudio::ActiveState:
soundState = 1;
break;
case QAudio::SuspendedState:
soundState = 2;
break;
case QAudio::StoppedState:
soundState = 0;
soundStateExpected=0;
if(loopCountdown==1 || isStopping){ //if this was the last loop or the user request to stop
if(fadeTimer.isActive()) fadeTimer.stop();
if(!isPlayer){
isStopping=true;
audio->disconnect(this);
emit(exitWaitingLoop());
emit(deleteMe(id));
this->disconnect();
}else{
audio->stop();
loopCountdown=loopSaved; //Recharge number of loops
if(buffer) buffer->seek(0);
}
}else{
if(loopCountdown>1) loopCountdown--;
if(buffer) buffer->seek(0);
play();
}
break;
case QAudio::IdleState:
soundState = 0;
soundStateExpected=0;
if(loopCountdown==1 || isStopping){ //if this was the last loop or the user request to stop
if(fadeTimer.isActive()) fadeTimer.stop();
if(!isPlayer){
isStopping=true;
audio->disconnect(this);
audio->stop();
emit(exitWaitingLoop());
emit(deleteMe(id));
this->disconnect();
}else{
audio->stop();
loopCountdown=loopSaved; //Recharge number of loops
if(buffer) buffer->seek(0);
}
}else{
if(loopCountdown>1) loopCountdown--;
if(buffer) buffer->seek(0);
play();
}
break;
}
}
void Sound::systemMassCommand(int i){
//0 - stop all playing sounds
//1 - play/resume all sounds paused with previous soundsystem(2) command.
//2 - pause all playing sounds
//3 - stop and delete all sounds and players
//4 - play/resume all paused sounds
switch (i) {
case 0:
if(soundStateExpected == 1) stop();
break;
case 1:
if(isPausedBySystem) play();
break;
case 2:
if(soundStateExpected == 1){
pause();
isPausedBySystem = true;
}
break;
case 3:
stopsSoundsAndWaiting();
break;
case 4:
if(soundStateExpected == 2) play();
break;
}
}
void Sound::stopsSoundsAndWaiting(){
//This slot is connected to main sound system
//It is time to shutdown any activity
//We will do the entire job here, disconnecting signals
isStopping=true;
loopCountdown=1;
soundState = 0;
if(fadeTimer.isActive()) fadeTimer.stop();
if(audio){
audio->disconnect(this);
if(audio->state()==QAudio::SuspendedState || soundStateExpected == 2){
//Sometimes, if user request Pause, we need to start audio to properly stop and delete it
audio->start(buffer);
}
audio->stop();
emit(exitWaitingLoop());
emit(deleteMe(id));
this->disconnect();
}else if(media){
media->disconnect(this);
media->stop();
emit(exitWaitingLoop());
media->setMedia(QMediaContent());
emit(deleteMe(id));
this->disconnect();
}
}
//Fade effect
void Sound::timerEvent(QTimerEvent *event){
if (event->timerId() == fadeTimer.timerId()) {
if(soundState==1){//only while it is playing
if(fadeDelayCountdown <=0 ){
fadeCountdown--;
if(fadeCountdown<=0){
individualVolume=fadeVolume;
}else{
individualVolume+=(fadeVolume-individualVolume)/(double)fadeCountdown;
}
if(audio){
audio->setVolume((qreal)(masterVolume/10.0*individualVolume));
}else if(media){
media->setVolume(masterVolume*10*individualVolume);
}
if(fadeCountdown<=0 || individualVolume==fadeVolume){
fadeTimer.stop();
}
}else{
fadeDelayCountdown--;
}
}
} else {
QObject::timerEvent(event);
}
}
// ##########################################################################################
// ##########################################################################################
SoundSystem::SoundSystem() :
QObject()
{
error=NULL;
soundSystemIsStopping = false;
lastIdUsed=0;
soundID=0;
lastBeepLoaded=0;
sound_envelope_length=0;
sound_envelope_release=0;
sound_envelope_release_bit=0.0;
sound_harmonics[1] = 1.0; //set the fundamental tone / 1st harmonic to full amplitude
SETTINGS;
setMasterVolume(settings.value(SETTINGSSOUNDVOLUME, SETTINGSSOUNDVOLUMEDEFAULT).toInt());
sound_samplerate = settings.value(SETTINGSSOUNDSAMPLERATE, SETTINGSSOUNDSAMPLERATEDEFAULT).toInt();
sound_normalize_ms = settings.value(SETTINGSSOUNDNORMALIZE, SETTINGSSOUNDNORMALIZEDEFAULT).toInt();
sound_fade_ms = settings.value(SETTINGSSOUNDVOLUMERESTORE, SETTINGSSOUNDVOLUMERESTOREDEFAULT).toInt();
// setup the audio format
format.setSampleRate(sound_samplerate);
format.setChannelCount(1);
format.setSampleSize(16); // 16 bit audio
format.setCodec("audio/pcm");
format.setSampleType(QAudioFormat::SignedInt);
// debugging - list available devices
//QList<QAudioDeviceInfo> devices = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput);
//foreach (QAudioDeviceInfo i, devices) {
// fprintf(stderr, i.deviceName().toUtf8().constData());
// fprintf(stderr, "\n");
//}
QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
if (!info.isFormatSupported(format)) {
format = info.nearestFormat(format);
#ifdef DEBUG
fprintf(stderr,"Switching to nearest audio format.\n");
#endif
}
int i;
double bit, pos;
//Generate sin waveform
waveformsin = new int16_t[sound_samplerate];
bit = 2 * 4*atan(1.0) / ((double) sound_samplerate); //pi = 4*atan(1.0);
for(i = 0; i < sound_samplerate; i++) {
waveformsin[i]=(int16_t) (SOUND_HALFWAVE * sin(bit * (double)i));
}
//Generate square waveform
//waveformsquare = new int16_t[sound_samplerate];
//for(i = 0; i < sound_samplerate/2; i++) {
// waveformsquare[i]=(int16_t) SOUND_HALFWAVE;
//}
//for(; i < sound_samplerate; i++) {
// waveformsquare[i]=(int16_t) -SOUND_HALFWAVE;
//}
//Generate triangle waveform
//waveformtriangle = new int16_t[sound_samplerate];
//bit = SOUND_HALFWAVE / ((double) sound_samplerate) * 4.0;
//pos=0.0;
//for(i = 0; i < sound_samplerate/4; i++) {
// waveformtriangle[i]=(int16_t) pos;
// pos+=bit;
//}
//for(; i < sound_samplerate/4*3; i++) {
// waveformtriangle[i]=(int16_t) pos;
// pos-=bit;
//}
//for(; i < sound_samplerate; i++) {
// waveformtriangle[i]=(int16_t) pos;
// pos+=bit;
//}
//Generate saw waveform
//waveformsaw = new int16_t[sound_samplerate];
//bit = SOUND_HALFWAVE * 2.0 / ((double) sound_samplerate);
//pos=0.0;
//for(i = 0; i < sound_samplerate/2; i++) {
// waveformsaw[i]=(int16_t) pos;
// pos+=bit;
//}
//pos=-SOUND_HALFWAVE;
//for(; i < sound_samplerate; i++) {
// waveformsaw[i]=(int16_t) pos;
// pos+=bit;
//}
//Generate pulse waveform
//waveformpulse = new int16_t[sound_samplerate];
//for(i = 0; i < sound_samplerate/10; i++) {
// waveformpulse[i]=(int16_t) SOUND_HALFWAVE;
//}
//for(; i < sound_samplerate; i++) {
// waveformpulse[i]=(int16_t) -SOUND_HALFWAVE;
//}
//Allocate space for waveformcustom (created by user)
//waveformcustom = new int16_t[sound_samplerate];
//Allocate space for sound wave mixed with harmonics
//waveformmixedwithharmonics = new int16_t[sound_samplerate];
currentwaveform = waveformsin; //default waveform = sin
mustUpdateWaveformSample = false;
waveformsample = waveformsin;
}
SoundSystem::~SoundSystem() {
exit();
//delete loaded sounds
QMap<QString, LoadedSound>::const_iterator i = loadedsounds.constBegin();
while (i != loadedsounds.constEnd()) {
delete(i.value().byteArray);
++i;
}
loadedsounds.clear();
delete[] waveformsin;
//delete[] waveformsquare;
//delete[] waveformtriangle;
//delete[] waveformsaw;
//delete[] waveformpulse;
//delete[] waveformcustom;
//delete[] waveformmixedwithharmonics;
}
void SoundSystem::deleteMe(int id){
if(soundsmap.count(id)){
disconnect(this, 0, soundsmap[id], 0);
soundsmap[id]->deleteLater();
soundsmap.erase(id);
}
}
void SoundSystem::validateLoadedSound(QString source, bool v){
//Validate loaded file only once.
//See waitLoadedMediaValidation() for details.
if(loadedsounds.count(source)){
loadedsounds[source].needValidation = false;
loadedsounds[source].isValidated = v;
}
}
void SoundSystem::exit(){
if(soundSystemIsStopping) return;
soundSystemIsStopping = true; // no more new sounds
//stop everything
emit(stopsSoundsAndWaiting());
}
int SoundSystem::playSound(QString s, bool isPlayer){
soundID=0;
if(soundsmap.size() >= SOUND_MAX_INSTANCES){
if(*error)(*error)->q(ERROR_TOOMANYSOUNDS);
return 0;
}
if(soundSystemIsStopping) return 0;
QUrl url(s);
if(s.startsWith("sound:")){
if(loadedsounds.count(s)){
lastIdUsed++;
//Do not play a loaded sound that is not a valid one
//(play if sound is validated already or try to play for the first time)
if(loadedsounds[s].needValidation || loadedsounds[s].isValidated){
//play only if loaded file is a valid one or if need validation
soundsmap[lastIdUsed] = new Sound(this);
soundsmap[lastIdUsed]->id = lastIdUsed;
soundsmap[lastIdUsed]->error = error;
soundsmap[lastIdUsed]->isPlayer = isPlayer; //set if this is a player that not delete sound at stop
connect(this, SIGNAL(stopsSoundsAndWaiting()), soundsmap[lastIdUsed], SLOT(stopsSoundsAndWaiting()));
connect(this, SIGNAL(systemMassCommand(int)), soundsmap[lastIdUsed], SLOT(systemMassCommand(int)));
connect(soundsmap[lastIdUsed], SIGNAL(deleteMe(int)), this, SLOT(deleteMe(int)));
connect(soundsmap[lastIdUsed], SIGNAL(validateLoadedSound(QString, bool)), this, SLOT(validateLoadedSound(QString, bool)));
soundsmap[lastIdUsed]->media = new QMediaPlayer(soundsmap[lastIdUsed]);
soundsmap[lastIdUsed]->individualVolume = loadedsounds[s].individualVolume;
soundsmap[lastIdUsed]->updatedMasterVolume(masterVolume);
soundsmap[lastIdUsed]->type = SOUNDTYPE_MEMORY;
soundsmap[lastIdUsed]->source = s;
soundsmap[lastIdUsed]->prepareConnections();
soundsmap[lastIdUsed]->buffer = new QBuffer(loadedsounds[s].byteArray);
soundsmap[lastIdUsed]->buffer->open(QIODevice::ReadOnly);
soundsmap[lastIdUsed]->buffer->seek(0);
soundsmap[lastIdUsed]->needValidation = loadedsounds[s].needValidation;
soundsmap[lastIdUsed]->isValidated = loadedsounds[s].isValidated;
soundsmap[lastIdUsed]->media->setMedia(QMediaContent(), soundsmap[lastIdUsed]->buffer);
soundsmap[lastIdUsed]->scheduledFade=loadedsounds[s].scheduledFade;
soundsmap[lastIdUsed]->fadeVolume=loadedsounds[s].fadeVolume;
soundsmap[lastIdUsed]->fadeCountdown=loadedsounds[s].fadeCountdown;
soundsmap[lastIdUsed]->fadeDelayCountdown=loadedsounds[s].fadeDelayCountdown;
soundsmap[lastIdUsed]->loopSaved=loadedsounds[s].loop;
soundsmap[lastIdUsed]->loopCountdown=loadedsounds[s].loop;
if(!isPlayer){
soundsmap[lastIdUsed]->play(); //if is a regular sound then play it, if is a player, then do not play it
}
soundID=lastIdUsed;
}
}else{
//there is no resource loaded with that ID
if(*error)(*error)->q(ERROR_SOUNDRESOURCE);
}
}else if(s.startsWith("beep:")){
if(loadedsounds.count(s)){
lastIdUsed++;
soundsmap[lastIdUsed] = new Sound(this);
soundsmap[lastIdUsed]->id = lastIdUsed;
soundsmap[lastIdUsed]->error = error;
soundsmap[lastIdUsed]->isPlayer = isPlayer; //set if this is a player that not delete sound at stop
connect(this, SIGNAL(stopsSoundsAndWaiting()), soundsmap[lastIdUsed], SLOT(stopsSoundsAndWaiting()));
connect(this, SIGNAL(systemMassCommand(int)), soundsmap[lastIdUsed], SLOT(systemMassCommand(int)));
connect(soundsmap[lastIdUsed], SIGNAL(deleteMe(int)), this, SLOT(deleteMe(int)));
//use this only when we gonna use QMediaPlayer instead of QAudioOutput (QAudioOutput intialization error)
//connect(soundsmap[lastIdUsed], SIGNAL(validateLoadedSound(QString, bool)), this, SLOT(validateLoadedSound(QString, bool)));
soundsmap[lastIdUsed]->type = SOUNDTYPE_MEMORY;
soundsmap[lastIdUsed]->source = s;
soundsmap[lastIdUsed]->buffer = new QBuffer(loadedsounds[s].byteArray);
soundsmap[lastIdUsed]->buffer->open(QIODevice::ReadOnly);
soundsmap[lastIdUsed]->buffer->seek(0);
soundsmap[lastIdUsed]->audio = new QAudioOutput(format,soundsmap[lastIdUsed]);
soundsmap[lastIdUsed]->individualVolume = loadedsounds[s].individualVolume;
soundsmap[lastIdUsed]->updatedMasterVolume(masterVolume);
soundsmap[lastIdUsed]->sound_samplerate=sound_samplerate;
soundsmap[lastIdUsed]->prepareConnections();
soundsmap[lastIdUsed]->scheduledFade=loadedsounds[s].scheduledFade;
soundsmap[lastIdUsed]->fadeVolume=loadedsounds[s].fadeVolume;
soundsmap[lastIdUsed]->fadeCountdown=loadedsounds[s].fadeCountdown;
soundsmap[lastIdUsed]->fadeDelayCountdown=loadedsounds[s].fadeDelayCountdown;
soundsmap[lastIdUsed]->loopSaved=loadedsounds[s].loop;
soundsmap[lastIdUsed]->loopCountdown=loadedsounds[s].loop;
//use this only when we gonna use QMediaPlayer instead of QAudioOutput (QAudioOutput intialization error)
//soundsmap[lastIdUsed]->needValidation = false;
//soundsmap[lastIdUsed]->isValidated = true;
if(!isPlayer){
soundsmap[lastIdUsed]->play(); //if is a regular sond then play it, if is a player, then do not play it
}
soundID=lastIdUsed;
}else{
//there is no resource loaded with that ID
if(*error)(*error)->q(ERROR_SOUNDRESOURCE);
}
}else if(QFileInfo(s).exists()){
lastIdUsed++;
soundsmap[lastIdUsed] = new Sound(this);
soundsmap[lastIdUsed]->id = lastIdUsed;
soundsmap[lastIdUsed]->error = error;
soundsmap[lastIdUsed]->isPlayer = isPlayer; //set if this is a player that not delete sound at stop
connect(this, SIGNAL(stopsSoundsAndWaiting()), soundsmap[lastIdUsed], SLOT(stopsSoundsAndWaiting()));
connect(this, SIGNAL(systemMassCommand(int)), soundsmap[lastIdUsed], SLOT(systemMassCommand(int)));
connect(soundsmap[lastIdUsed], SIGNAL(deleteMe(int)), this, SLOT(deleteMe(int)));
soundsmap[lastIdUsed]->media = new QMediaPlayer(soundsmap[lastIdUsed]);
soundsmap[lastIdUsed]->type = SOUNDTYPE_FILE;
soundsmap[lastIdUsed]->source = s;
soundsmap[lastIdUsed]->prepareConnections();
//there are cases when an invalid file as "text.txt" is not detected as QMediaPlayer::InvalidMedia and signal is not emitted
//If we stop a program like below, program freezes when we try to delete this kind of sound... we should request validation
// i= 100000
// x=soundplay("license.txt")
// loop:
// i=i-1 : soundpause : soundplay
// print soundposition ; " " ; (100000-i)
// if i > 0 then goto loop
soundsmap[lastIdUsed]->needValidation = true;
soundsmap[lastIdUsed]->isValidated = false;
soundsmap[lastIdUsed]->media->setMedia(QUrl::fromLocalFile(QFileInfo(s).absoluteFilePath()));
soundsmap[lastIdUsed]->updatedMasterVolume(masterVolume);
if(!isPlayer) soundsmap[lastIdUsed]->play(); //if it is a regular sound then play it, if it is a player, then do not play it
soundID=lastIdUsed;
}else if (url.isValid() && (url.scheme()=="http" || url.scheme()=="https" || url.scheme()=="ftp")){
lastIdUsed++;
soundsmap[lastIdUsed] = new Sound(this);
soundsmap[lastIdUsed]->id = lastIdUsed;
soundsmap[lastIdUsed]->error = error;
soundsmap[lastIdUsed]->isPlayer = isPlayer; //set if this is a player that not delete sound at stop
connect(this, SIGNAL(stopsSoundsAndWaiting()), soundsmap[lastIdUsed], SLOT(stopsSoundsAndWaiting()));
connect(this, SIGNAL(systemMassCommand(int)), soundsmap[lastIdUsed], SLOT(systemMassCommand(int)));
connect(soundsmap[lastIdUsed], SIGNAL(deleteMe(int)), this, SLOT(deleteMe(int)));
soundsmap[lastIdUsed]->media = new QMediaPlayer(soundsmap[lastIdUsed]);
soundsmap[lastIdUsed]->type = SOUNDTYPE_WEB;
soundsmap[lastIdUsed]->source = s;
soundsmap[lastIdUsed]->prepareConnections();
soundsmap[lastIdUsed]->media->setMedia(QUrl::fromUserInput(s));
soundsmap[lastIdUsed]->updatedMasterVolume(masterVolume);
//see above
soundsmap[lastIdUsed]->needValidation = true;
soundsmap[lastIdUsed]->isValidated = false;
if(!isPlayer) soundsmap[lastIdUsed]->play(); //if is a regular sond then play it, if is a player, then do not play it
soundID=lastIdUsed;
}else{
//Unable to load sound file
if(*error)(*error)->q(ERROR_SOUNDFILE);
}
return soundID;
}
int SoundSystem::playSound(std::vector<std::vector<double>> sounddata, bool isPlayer) {
soundID=0;
if(soundSystemIsStopping) return 0;
lastIdUsed++;
soundsmap[lastIdUsed] = new Sound(this);
soundsmap[lastIdUsed]->id = lastIdUsed;
soundsmap[lastIdUsed]->error = error;
soundsmap[lastIdUsed]->isPlayer = isPlayer; //set if this is a player that not delete sound at stop
connect(this, SIGNAL(stopsSoundsAndWaiting()), soundsmap[lastIdUsed], SLOT(stopsSoundsAndWaiting()));
connect(this, SIGNAL(systemMassCommand(int)), soundsmap[lastIdUsed], SLOT(systemMassCommand(int)));
connect(soundsmap[lastIdUsed], SIGNAL(deleteMe(int)), this, SLOT(deleteMe(int)));
soundsmap[lastIdUsed]->byteArray = generateSound(sounddata);
soundsmap[lastIdUsed]->buffer = new QBuffer(soundsmap[lastIdUsed]->byteArray);
soundsmap[lastIdUsed]->buffer->open(QIODevice::ReadWrite);
soundsmap[lastIdUsed]->buffer->seek(0);
soundsmap[lastIdUsed]->type = SOUNDTYPE_GENERATED;
soundsmap[lastIdUsed]->audio = new QAudioOutput(format,soundsmap[lastIdUsed]);
soundsmap[lastIdUsed]->updatedMasterVolume(masterVolume);
soundsmap[lastIdUsed]->sound_samplerate=sound_samplerate;
soundsmap[lastIdUsed]->prepareConnections();
//use this only when we gonna use QMediaPlayer instead of QAudioOutput (QAudioOutput intialization error)
//soundsmap[lastIdUsed]->needValidation = false;
//soundsmap[lastIdUsed]->isValidated = true;
if(!isPlayer) soundsmap[lastIdUsed]->play(); //if is a regular sond then play it, if is a player, then do not play it
soundID=lastIdUsed;
return soundID;
}
void SoundSystem::loadSoundFromArray(QString id, QByteArray* arr){
if (loadedsounds.contains(id)) delete(loadedsounds[id].byteArray);
loadedsounds[id].byteArray = new QByteArray(*arr);
//file loaded into memory... need validation at first play
loadedsounds[id].needValidation = true;
loadedsounds[id].isValidated = false;
loadedsounds[id].individualVolume = 1.0;
loadedsounds[id].scheduledFade = false;
loadedsounds[id].fadeVolume=1.0;
loadedsounds[id].fadeCountdown=0;
loadedsounds[id].fadeDelayCountdown=0;
loadedsounds[id].loop=1;
}
QString SoundSystem::loadSoundFromVector(std::vector<std::vector<double> > sounddata) {
//generate a sound, load it into memory and return ID of loaded resource like "beep:23"
lastBeepLoaded++;
QString id = QString("beep:") + QString::number(lastBeepLoaded);
if (loadedsounds.contains(id)) delete(loadedsounds[id].byteArray);
loadedsounds[id].byteArray = generateSound(sounddata);
//we don´t need a validation - it is not a media file, but the next step is to use QMediaPlayer instead of QAudioOutput when QAudioOutput fails at initialization
loadedsounds[id].needValidation = false;
loadedsounds[id].isValidated = true;
loadedsounds[id].individualVolume = 1.0;
loadedsounds[id].scheduledFade = false;
loadedsounds[id].fadeVolume=1.0;
loadedsounds[id].fadeCountdown=0;
loadedsounds[id].fadeDelayCountdown=0;
loadedsounds[id].loop=1;
return id;
}
QString SoundSystem::loadRaw(std::vector<double> raw) {
//build a sound from raw data, load it into memory and return ID of loaded resource like "beep:23"
const int size = raw.size();
std::vector<int16_t> sounddata;
sounddata.resize(size);
for(int i=0;i<size;i++){
double d = raw[i];
if(d>1.0)d=1.0;
if(d<-1.0)d=-1.0;
sounddata[i]=d*SOUND_HALFWAVE;
}
lastBeepLoaded++;
QString id = QString("beep:") + QString::number(lastBeepLoaded);
loadedsounds[id].byteArray = new QByteArray(reinterpret_cast<const char*>(sounddata.data()), size*sizeof(int16_t));
//we don´t need a validation - it is not a media file, but the next step is to use QMediaPlayer instead of QAudioOutput when QAudioOutput fails at initialization
loadedsounds[id].needValidation = false;
loadedsounds[id].isValidated = true;
loadedsounds[id].individualVolume = 1.0;
loadedsounds[id].scheduledFade = false;
loadedsounds[id].fadeVolume=1.0;
loadedsounds[id].fadeCountdown=0;
loadedsounds[id].fadeDelayCountdown=0;
loadedsounds[id].loop=1;
return id;
}
bool SoundSystem::unloadSound(QString id){
if (loadedsounds.contains(id)){
for (auto it = soundsmap.begin(); it != soundsmap.end(); ){
if(it->second->source == id){
if(it->second->soundState != 0) it->second->stop();
delete(it->second);
soundsmap.erase(it++);
}else{
++it;
}
}
delete(loadedsounds[id].byteArray);
loadedsounds.remove(id);
return true;
}
return false;
}
QByteArray* SoundSystem::generateSound(std::vector<std::vector<double>> sounddata) {
// mix lists of sounds in the to be played in the same time (mixed sounds)
// the vector or vectors soundata contains a vector for each voice