voice activity detection in noise using deep learning -凯发k8网页登录
in this example, you perform batch and streaming voice activity detection (vad) in a low snr environment using a pretrained deep learning model. for details about the model and how it was trained, see .
load and inspect data
read in an audio file that consists of words spoken with pauses between and listen to it. use to resample the signal to the sample rate to 16 khz. use on the clean signal to determine the ground-truth speech regions.
fs = 16e3; [speech,filefs] = audioread("counting-16-44p1-mono-15secs.wav"); speech = resample(speech,fs,filefs); speech = speech./max(abs(speech)); sound(speech,fs) detectspeech(speech,fs,window=hamming(0.04*fs,"periodic"),mergedistance=round(0.5*fs))
load a noise signal and to the audio sample rate.
[noise,filefs] = audioread("washingmachine-16-8-mono-200secs.mp3");
noise = resample(noise,fs,filefs);
use the supporting function to corrupt the clean speech signal with washing machine noise at a desired snr level in db. listen to the corrupted audio. the network was trained under -10 db snr conditions.
snr = -10;
noisyspeech = mixsnr(speech,noise,snr);
sound(noisyspeech,fs)
the algorithm-based vad, , fails under these noisy conditions.
detectspeech(noisyspeech,fs,window=hamming(0.04*fs,"periodic"),mergedistance=round(0.5*fs))
download pretrained network
download and load a pretrained network and a configured audiofeatureextractor
object. the network was trained to detect speech in low snr environments given features output from the audiofeatureextractor
object.
downloadfolder = matlab.internal.examples.downloadsupportfile("audio","voiceactivitydetection.zip"); datafolder = tempdir; unzip(downloadfolder,datafolder) netfolder = fullfile(datafolder,"voiceactivitydetection"); pretrainednetwork = load(fullfile(netfolder,"voiceactivitydetectionexample.mat")); afe = pretrainednetwork.afe; net = pretrainednetwork.speechdetectnet;
the audiofeatureextractor
object is configured to extract features from 256-sample windows with 128 samples overlap between windows. at a 16 khz sample rate, features are extracted from 16 ms windows with 8 ms overlap. from each window, the audiofeatureextractor
object extracts nine features: spectral centroid, spectral crest, spectral entropy, spectral flux, spectral kurtosis, spectral rolloff point, spectral skewness, spectral slope, and harmonic ratio.
afe
afe = audiofeatureextractor with properties: properties window: [256×1 double] overlaplength: 128 samplerate: 16000 fftlength: [] spectraldescriptorinput: 'linearspectrum' featurevectorlength: 9 enabled features spectralcentroid, spectralcrest, spectralentropy, spectralflux, spectralkurtosis, spectralrolloffpoint spectralskewness, spectralslope, harmonicratio disabled features linearspectrum, melspectrum, barkspectrum, erbspectrum, mfcc, mfccdelta mfccdeltadelta, gtcc, gtccdelta, gtccdeltadelta, spectraldecrease, spectralflatness spectralspread, pitch, zerocrossrate, shorttimeenergy to extract a feature, set the corresponding property to true. for example, obj.mfcc = true, adds mfcc to the list of enabled features.
the network consists of two bidirectional lstm layers, each with 200 hidden units, and a classification output that returns either class 0 corresponding to no voice activity detected or class 1 corresponding to voice activity detected.
net.layers
ans = 6×1 layer array with layers: 1 'sequenceinput' sequence input sequence input with 9 dimensions 2 'bilstm_1' bilstm bilstm with 200 hidden units 3 'bilstm_2' bilstm bilstm with 200 hidden units 4 'fc' fully connected 2 fully connected layer 5 'softmax' softmax softmax 6 'classoutput' classification output crossentropyex with classes '0' and '1'
perform voice activity detection
extract features from the speech data and then standardize them. orient the features so that time is across columns.
features = extract(afe,noisyspeech); features = (features - mean(features,1))./std(features,[],1); features = features';
pass the features through the speech detection network to classify each feature vector as belonging to a frame of speech or not.
decisionscategorical = classify(net,features);
each decision corresponds to an analysis window analyzed by the audiofeatureextractor
. replicate the decisions so that they are in one-to-one correspondence with the audio samples. use the convenience plot to plot the ground truth. use and to plot the predicted vad.
decisions = (double(decisionscategorical) - 1)'; decisionspersample = [decisions(1:round(numel(afe.window)/2));repelem(decisions,numel(afe.window)-afe.overlaplength,1)]; tiledlayout(2,1) nexttile detectspeech(speech,fs,window=hamming(0.04*fs,"periodic"),mergedistance=round(0.5*fs)) title("ground truth vad") xlabel("") nexttile mask = signalmask(decisionspersample,samplerate=fs,categories="activity"); plotsigroi(mask,noisyspeech,true) title("predicted vad")
perform streaming voice activity detection
the audiofeatureextractor
object is intended for batch processing and does not retain state between calls. use to create a streaming-friendly feature extractor. you can use the trained vad network in a streaming context using (deep learning toolbox).
generatematlabfunction(afe,"featureextractor",isstreaming=true)
to simulate a streaming environment, save the speech and noise signals as wav files. to simulate streaming input, you will use to read frames from the files and mix them at a desired snr. you can also use so that your microphone is the speech source.
audiowrite("speech.wav",speech,fs) audiowrite("noise.wav",noise,fs)
define parameters for the streaming voice activity detection in noise demonstration:
signal
- signal source, specified as either the speech file previously recorded, or your microphone.noise
- noise source, specified as a noise sound file to mix with the signal.snr
- signal-to-noise ratio to mix the signal and noise, specified in db.testduration
- test duration, specified in seconds.playbacksource
- playback source, specified as either the original clean signal, the noisy signal, or the detected speech. an object is used to play the audio to your speakers.
signal = "speech.wav"; noise = "noise.wav"; snr = -10; % db testduration = 20; % seconds playbacksource = "noisy";
call the supporting function to observe the performance of the vad network on streaming audio. the parameters you set using the live controls do not interrupt the streaming example. after the streaming demo is complete, you can modify parameters of the demonstration, then run the streaming demo again.
streamingdemo(net,afe, ... signal,noise,snr, ... testduration,playbacksource);
references
[1] warden p. "speech commands: a public dataset for single-word speech recognition", 2017. available from . 凯发官网入口首页 copyright google 2017. the speech commands dataset is licensed under the creative commons attribution 4.0 license
supporting functions
streaming demo
function streamingdemo(net,afe,signal,noise,snr,testduration,playbacksource) % streamingdemo(net,afe,signal,noise,snr,testduration,playbacksource) runs % a real-time vad demo. % create dsp.audiofilereader objects to read speech and noise files frame % by frame. if the speech signal is specified as microphone, use an % audiodevicereader as the source. if strcmpi(signal,"microphone") speechreader = audiodevicereader(afe.samplerate); else speechreader = dsp.audiofilereader(signal,playcount=inf); end noisereader = dsp.audiofilereader(noise,playcount=inf,samplesperframe=speechreader.samplesperframe); fs = speechreader.samplerate; % create a dsp.movingstandarddeviation object and a dsp.movingaverage % object. you will use these to determine the standard deviation and mean % of the audio features for standardization. the statistics should improve % over time. movstd = dsp.movingstandarddeviation(method="exponential weighting",forgettingfactor=1); movmean = dsp.movingaverage(method="exponential weighting",forgettingfactor=1); % create a dsp.movingmaximum object. you will use it to standardize the % audio. movmax = dsp.movingmaximum(specifywindowlength=false); % create a dsp.movingrms object. you will use this to determine the signal % and noise mix at the desired snr. this object is only useful for example % purposes where you are artificially adding noise. movrms = dsp.movingrms(method="exponential weighting",forgettingfactor=1); % create three dsp.asyncbuffer objects. one to buffer the input audio, one % to buffer the extracted features, and one to buffer the output audio so % that vad decisions correspond to the audio signal. the output buffer is % only necessary for visualizing the decisions in real time. audioinbuffer = dsp.asyncbuffer(2*speechreader.samplesperframe); featurebuffer = dsp.asyncbuffer(ceil(2*speechreader.samplesperframe/(numel(afe.window)-afe.overlaplength))); audiooutbuffer = dsp.asyncbuffer(2*speechreader.samplesperframe); % create a time scope to visualize the original speech signal, the noisy % signal that the network is applied to, and the decision output from the % network. scope = timescope(samplerate=fs, ... timespansource="property", ... timespan=3, ... bufferlength=fs*3*3, ... timespanoverrunaction="scroll", ... axesscaling="updates", ... maximizeaxes="on", ... axesscalingnumupdates=20, ... numinputports=3, ... layoutdimensions=[3,1], ... channelnames=["noisy speech","clean speech (original)","detected speech"], ... ... activedisplay = 1, ... showgrid=true, ... ... activedisplay = 2, ... showgrid=true, ... ... activedisplay=3, ... showgrid=true); %#oksetup(scope,{1,1,1}) % create an audiodevicewriter object to play either the original or noisy % audio from your speakers. devicewriter = audiodevicewriter(samplerate=fs); % initialize variables used in the loop. windowlength = numel(afe.window); hoplength = windowlength - afe.overlaplength; % run the streaming demonstration. looptimer = tic; while toc(looptimer) < testduration % read a frame of the speech signal and a frame of the noise signal speechin = speechreader(); noisein = noisereader(); % mix the speech and noise at the specified snr energy = movrms([speechin,noisein]); noisegain = 10^(-snr/20) * energy(end,1) / energy(end,2); noisyaudio = speechin noisegain*noisein; % update a running max to scale the audio mymax = movmax(abs(noisyaudio)); noisyaudio = noisyaudio/mymax(end); % write the noisy audio and speech to buffers write(audioinbuffer,[noisyaudio,speechin]); % if enough samples are in the audio buffer to calculate a feature % vector, read the samples, normalize them, extract the feature % vectors, and write the latest feature vector to the features buffer. while (audioinbuffer.numunreadsamples >= hoplength) x = read(audioinbuffer,numel(afe.window),afe.overlaplength); write(audiooutbuffer,x(end-hoplength 1:end,:)); noisyaudio = x(:,1); features = featureextractor(noisyaudio); write(featurebuffer,features'); end if featurebuffer.numunreadsamples >= 1 % read the audio data corresponding to the number of unread % feature vectors. audiohop = read(audiooutbuffer,featurebuffer.numunreadsamples*hoplength); % read all unread feature vectors. features = read(featurebuffer); % use only the new features to update the standard deviation and % mean. normalize the features. rmean = movmean(features); rstd = movstd(features); features = (features - rmean(end,:)) ./ rstd(end,:); % network inference [net,decision] = classifyandupdatestate(net,features'); % convert the decisions per feature vector to decisions per sample decision = repelem(decision,hoplength,1); % apply a mask to the noisy speech for visualization vadresult = audiohop(:,1); vadresult(decision==categorical(0)) = 0; % listen to the speech or speech noise switch playbacksource case "clean" devicewriter(audiohop(:,2)); case "noisy" devicewriter(audiohop(:,1)); case "detectedspeech" devicewriter(vadresult); end % visualize the speech noise, the original speech, and the voice % activity detection. scope(audiohop(:,1),audiohop(:,2),vadresult) end end end
mix snr
function [noisysignal,requestednoise] = mixsnr(signal,noise,ratio) % [noisysignal,requestednoise] = mixsnr(signal,noise,ratio) returns a noisy % version of the signal, noisysignal. the noisy signal has been mixed with % noise at the specified ratio in db. numsamples = size(signal,1); % convert noise to mono noise = mean(noise,2); % trim or expand noise to match signal size if size(noise,1)>=numsamples % choose a random starting index such that you still have numsamples % after indexing the noise. start = randi(size(noise,1) - numsamples 1); noise = noise(start:start numsamples-1); else numreps = ceil(numsamples/size(noise,1)); temp = repmat(noise,numreps,1); start = randi(size(temp,1) - numsamples - 1); noise = temp(start:start numsamples-1); end signalnorm = norm(signal); noisenorm = norm(noise); goalnoisenorm = signalnorm/(10^(ratio/20)); factor = goalnoisenorm/noisenorm; requestednoise = noise.*factor; noisysignal = signal requestednoise; noisysignal = noisysignal./max(abs(noisysignal)); end