Android.media.AudioTrack:PcmTest
Android AudioTrack PCM Testing Code.
package ---;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import android.app.Activity;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Jjack extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button play;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
play=new Button(this);
play.setText("Play");
play.setOnClickListener(this);
setContentView(play);
// setContentView(R.layout.main);
}
@Override
public void onClick(View arg0) {
// new AudioSynth01();
//A buffer to hold two seconds monaural and one
// second stereo data at 16000 samp/sec for
// 16-bit samples
byte audioData[] = new byte[16000*4];
//The following are audio format parameters.
// They may be modified by the signal generator
// at runtime. Values allowed by Java
// SDK 1.4.1 are shown in comments.
//TODO
float sampleRate =8000.0F;// 16000.0F;
//Allowable 8000,11025,16000,22050,44100
// int sampleSizeInBits = 16;
//Allowable 8,16
// int channels = 1;
//Allowable 1,2
//Each channel requires two 8-bit bytes per
// 16-bit sample.
int bytesPerSamp = 2;
// boolean signed = true;
//Allowable true,false
// boolean bigEndian = true;
//Allowable true,false
ByteBuffer byteBuffer = ByteBuffer.wrap(audioData);
ShortBuffer shortBuffer = byteBuffer.asShortBuffer();
int byteLength = audioData.length;
int sampLength = byteLength/bytesPerSamp;
for(int cnt = 0; cnt < sampLength; cnt++){
double time = cnt/sampleRate;
double freq = 20000F;//950.0;//arbitrary frequency
double sinValue =
(Math.sin(2*Math.PI*freq*time) +
Math.sin(2*Math.PI*(freq/1.8)*time) +
Math.sin(2*Math.PI*(freq/1.5)*time))/3.0;
shortBuffer.put((short)(16000*sinValue));
}
try{
//Get an input stream on the byte array
// containing the data
InputStream byteArrayInputStream =
new ByteArrayInputStream(audioData);
//Get the required audio format
// AudioFormat audioFormat =
// new AudioFormat(
// sampleRate,
// sampleSizeInBits,
// channels,
// signed,
// bigEndian);
AudioTrack track= new AudioTrack( AudioManager.STREAM_MUSIC,
(int)sampleRate,
android.media.AudioFormat.CHANNEL_CONFIGURATION_MONO,
android.media.AudioFormat.ENCODING_PCM_16BIT,
android.media.AudioTrack.getMinBufferSize( (int)sampleRate,
android.media.AudioFormat.CHANNEL_CONFIGURATION_STEREO,
android.media.AudioFormat.ENCODING_PCM_16BIT ),
AudioTrack.MODE_STREAM );
track.play();
int cnt;
byte buff[]=new byte[1024];
while((cnt=byteArrayInputStream.read(buff))>0)
track.write(buff, 0, cnt);
}catch (Exception e) {
}//end catch
// TODO code application logic here
}
}