19 Halve the speed of the audio clip

Imagine that the guitar player plays at half the speed that they were playing at in the original clip. If the sampling rate was kept constant, then the audio data would consist of almost double the number of samples as in the original clip.

Write a function named halfSpeed that returns a new audio vector that when played sounds like the original clip played at half the speed. The function should satisfy all of the following requirements:

  1. it should be named halfSpeed
  2. it should have one input variable called y which is an audio vector
  3. it should return a value named z
  4. the value that is returned should be the half speed audio vector that is computed using the steps described below
  5. it should have a help documentation comment

Suppose that the original audio vector has only 5 elements:

[5 -10 8 22 -4]

In the half speed version, the first and last elements of the half speed vector will be equal to the first and last elements of the original vector, and every second element of the half speed vector will be equal to an element in the original vector. We start by making a vector of 9 zeros:

[0 0 0 0 0 0 0 0 0]

We then set every second of element of the half speed vector to the elements in the original vector:

[5 0 -10 0 8 0 22 0 -4]

Now what values do we replace the 0s with? One possibility is to set the 0s to the average of the adjacent values in the original vector. That is, the first zero is replaced by the average of 5 and -10, the second zero is replaced by the average of -10 and 8, the third zero is replaced by the average of 8 and 22, and so on. Note that we can compute all of the average values like so:

([5 -10 8 22] + [-10 8 22 -4]) / 2

Replacing the zeros with the average values yields:

[5 -2.5 -10 -1 8 15 22 9 -4]

Your function halfSpeed should perform the steps described above using the input vector y. To make the vector of 0s, use the function zeros. All of the other steps can be accomplished using indexing.

Play the half speed version of the original audio clip like so:

z = halfSpeed(y);
sound(z, 16000);

The double speed version should play in the double the time of the original clip and sound lower in pitch.