Audio Synthesis
package app.test;
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Test extends Activity implements OnClickListener {
Button startSound,endSound;
AudioSynthesisTask audioSynth;
boolean keepGoing = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startSound = (Button) this.findViewById(R.id.StartSound);
startSound.setOnClickListener(this);
endSound = (Button) this.findViewById(R.id.EndSound);
endSound.setOnClickListener(this);
endSound.setEnabled(false);
}
@Override
public void onPause() {
super.onPause();
keepGoing = false;
endSound.setEnabled(false);
startSound.setEnabled(true);
}
public void onClick(View v) {
if (v == startSound) {
keepGoing = true;
audioSynth = new AudioSynthesisTask();
audioSynth.execute();
endSound.setEnabled(true);
startSound.setEnabled(false);
} else if (v == endSound) {
keepGoing = false;
endSound.setEnabled(false);
startSound.setEnabled(true);
}
}
private class AudioSynthesisTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
final int SAMPLE_RATE = 11025;
int minSize = AudioTrack.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT, minSize,
AudioTrack.MODE_STREAM);
audioTrack.play();
short[] buffer = { 1,2,3,4};
while (keepGoing) {
audioTrack.write(buffer, 0, buffer.length);
}
return null;
}
}
}
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/StartSound" android:text="Start Sound"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/EndSound" android:text="End Sound"></Button>
</LinearLayout>
Related examples in the same category