%sounddemo.m
%Cogent 2000 and MATLAB Sound Capabilities Demo (2015)
freq = 44100;
nchannels = 2;
nbits = 16;
nbuffers = 100;
config_sound(nchannels,nbits,freq,nbuffers);
config_display(0); %full-screen exclusive mode (=1) required!!!
                   %Note: Cogent 2000 sound commands are more robust
                   %in full screen mode (no window focus problems)
start_cogent;      %install Cogent 2000
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                           %
% Try demonstrating some sounds using Cogent 2000 commands  %
%                                                           %
% Note: These commands are very finicky.  Tests reveal      %
%       that much of their flakey behavior (technical term) %
%       stems from a problem with improper Window focus.    %
%       This suggests that more reliable performance can    %
%       be achieved when the sound commands are executed    %
%       in full screen (rather than window) display mode.   %
%                                                           %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%generate 2 seconds of white noise in buffer #1
preparewhitenoise(2000,1); %generate 2 sec of white noise
setsoundvol(1,0); %no volume attenuation
disp('Start playing noise...');
playsound(1);
waitsound(1);
disp('End of noise.');
disp(' ');
wait(1000);

%load and play brief 1500Hz tone
disp('Play TONE1500.WAV')
loadsound('tone1500.wav',2);
setsoundvol(2,-300); %3 dB volume attenuation
playsound(2);
f=getsoundfreq(2);
v=getsoundvol(2);
disp(['Freq = ',num2str(f)]);
disp(['Vol  = ',num2str(v)]);
disp(' ');
wait(1000);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                    %
% These matlab's sound commands work %
%                                    %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%first, play Handel's Messiah demo
load('handel'); %reads in: y-array, Fs=8192
disp('Start Synchronous Play of Handel');
%wavplay(y,Fs);    %synchronous play
p1 = audioplayer(y,Fs);
playblocking(p1);
disp('End Handel');
disp(' ')
wait(1000);
%
%next, generate 1000 Hz tone at 44100 sampling rate
disp('Play 1KHz tone');
Fs=44100;            %sampling freq
t=0:1/Fs:0.25;       %sampling timeline (duration=250ms)
y=sin(2*pi*1000*t);  %make 1000Hz tone data
%sound(y,Fs);         %asynchronously play brief tone
%wait(1000);          %wait 1 sec
p2 = audioplayer(y,Fs);
playblocking(p2);
disp('End of Sound Demo');
wait(1000);
%
%load a .WAV file and play it
disp(' ');
disp('Load .WAV file and play in synchronous mode');
[y,Fs]=audioread('notify.wav');
%wavplay(y,Fs);
p3 = audioplayer(y,Fs,nbits);
playblocking(p3);
disp(' ');

%synthesize random sound and play via Cogent 2000
disp('Synthesized Random Sound');
disp(' ');
synth = (rand(freq,nchannels)*2)-1;
preparesound(synth,3);
playsound(3);
wait(2000);

%uninstall Cogent 2000
stop_cogent;
