Home Tutorials Hints & Tips

Android Sine Wave Synthesis

Part 4 - PlayWave.java Methods

Preceding tutorials in this series:

Tutorials in that series that follow:

Now that the Constructor for the PlayWave.java class is built, we can go on to add the remaining methods for the class. Three methods are needed. One will calculate the samples for the sine wave at a given frequency, the second will start the playback of the wave and the final method will stop the playback of the wave. Since the theory of how we generate the wave was tested in the part 1 if this tutorial, we do not need to spend too much time reviewing this.

The approach I am taking is to generate samples for one period of a sine wave, load that into AudioTrack and repeat the sampled wave. Therefore, we need to know the number of samples for a given frequency. An integer variable sampleCount is defined. I have defined method in the PlayWave class called setWave. The frequency is passed to this method from the main activity. The following line of code is used to calculate the sample count:

sampleCount = (int) ((float) SAMPLE_RATE / frequency);

The result of SAMPLE_RATE / frequency returns a float value and we can then cast that as an integer to truncate the result. An array of type short is defined to hold the samples:

short samples[] = new short[sampleCount];

The Java short primitive supports integer values from -32768 to +32767. This is ideal for 16 bit PCM. The following code is the Java implementation of our pseudo code from part 1 and forms the integral part of the setWave method.

int amplitude = 32767;
double twopi = 8. * Math.atan(1.);
double phase = 0.0;

for (int i = 0; i < sampleCount; i++) {
 samples[i] = (short) (amplitude * Math.sin(phase));
 phase += twopi * frequency / SAMPLE_RATE;

The final task of the setWave method is the write the data into the AudioTrack instance mAudio.

mAudio.write(samples, 0, sampleCount);

The parameters identify the data to write (samples), the offset, 0 being the first sample and the length of the data. This is the sampleCount in or case.

The method to start playback is defined below:

public void start() {
 mAudio.reloadStaticData(0, sampleCount, -1);

The first task is to call mAudio.reloadStaticData(). This method instructs AudioTrack to reuse the data already loaded. In effect it rewinds it to the beginning. The loop points are set at the first sample (0), the end (sampleCount) and the parameter -1 indicates an infinite loop.

The method to stop the playback requires no explanation. Your completed PlayWave.java class should look similar to the one below.

The next tutorial looks at completing the MainActivity and testing the project.

Download the Project files

Privacy and Cookies Disclaimer Copyright
© 2015 - 2018 North Border Tech Training All rights reserved