Home Tutorials Hints & Tips

Android Sine Wave Synthesis

Part 3 - PlayWave.java Class Constructor

Preceding tutorials in this series:

Tutorials in that series that follow:

Now that the project framework is complete, we can start to build out the PlayWave.java class. To start with, we need a constructor for the class. We shall place the AudioTrack initialization code within the constructor so that it is executed when we create an instance of the class in the Main Activity.

The documentation for AudioTrack can be found here.  We can define an integer constant for the sample rate and set it to 44100 and also create an instance of AudioTrack and give it the name “mAudio”.

The parameters needed for the instance AudioTrack are as follows. At this stage we will allocate an integer variable “buffsize” for the buffer size.

AudioTrack (int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode)

Android defines a set of constants that help us assign values to these parameters. The values we need are:

We will have to import the AudioManager and AudioFormat classes to access these constants.

The final task to complete the class constructor will be to assign a value to the buffer size. You may know the you need, but Android provides a method within the AudioTrack class to calculate the minimum buffer size needed for any particular combination of AudioTrack parameters. The method and parameters are show below.

Int buffsize = AudioTrack.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);

At this point your PlayWave.java class should look similar to mine below.

The next task will be to create the PlayWave.java methods that will calculate the samples as well as  starting and stopping playback.

Download the Project files

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