%% Manipulate Audio Samples Using Wavetable Synthesizer
% Sample an audio file and save it to the Wavetable property of a wavetableSynthesizer System object™. Use the wavetable synthesizer to manipulate your audio sample.
% Read in an entire audio file. Clip out an interesting sound from the audio and then play it.

[audio,fs] = audioread('MainStreetOne-24-96-stereo-63secs.wav');

engine = audio(5.35e6:5.45e6);
sound(engine,fs)

%
% Create a wavetable synthesizer using your audio clip. The duration of the engine audio clip is numel(engine)/fs seconds. In the wavetableSynthesizer, set the Frequency property to 1/(clip duration). The generated signal now plays back at the same rate it was recorded at.

duration = numel(engine)/fs;
waveSynth = wavetableSynthesizer('Wavetable',engine,'SampleRate',fs, ...
    'Frequency',1/duration);

%
% Create an audioDeviceWriter to write to your audio device.

deviceWriter = audioDeviceWriter('SampleRate',fs);

%
% In a loop, play the wavetable synthesizer to your device. After three seconds, begin increasing the frequency of the wavetable synthesizer. After six seconds, begin decreasing the frequency of the wavetable synthesizer.

timeElapsed = 0;
while timeElapsed < 9
    audioWave = waveSynth();
    deviceWriter(audioWave);
    
    if (timeElapsed > 3) && (timeElapsed < 6)
        waveSynth.Frequency = waveSynth.Frequency + 0.001;
    elseif timeElapsed > 6
        waveSynth.Frequency = waveSynth.Frequency - 0.002;
    end
    
    timeElapsed = timeElapsed + waveSynth.SamplesPerFrame*(1/fs);
end

% Copyright 2012 The MathWorks, Inc.