An unsatisfactory Android synthesis hack I tested this morning, I know there is a less deprecated way of doing this, but for now I'm happy that I've got a sine tone working through Android for Processing in Eclispe:
//the tone is generated when you press the screen, it works on my utterly rubbish Arnova 10b G3, //which, despite umpteen resets, has crazed dysfunctional calibration on the touch screen - a total lemon.
package processing.test.ansynth;
import processing.core.*;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.app.Activity;
import android.graphics.Bitmap;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.os.Handler;
import java.io.*;
import java.util.*;
public class AnSynth extends PApplet {
public float sf;
// originally from http://marblemice.blogspot.com/2010/04/generate-and-play-tone-in-android.html
// and modified by Steve Pomeroy <steve@staticfree.info>
private final int duration = 3; // seconds
private final int sampleRate = 8000;
private final int numSamples = duration * sampleRate;
private final double sample[] = new double[numSamples];
private final double freqOfTone = 440; // hz
private final byte generatedSnd[] = new byte[2 * numSamples];
// Handler handler = new Handler();
public void setup(){ genTone(); playSound();
}
public void draw(){
background(0, 0, 255);
fill(255, 0, 0);
ellipse(width/2, height/2,80, 80);
if(mousePressed){
genTone();
playSound();
}
}
Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
}
@Override
protected void onResume() {
super.onResume();
// Use a new tread as this can take a while
final Thread thread = new Thread(new Runnable() {
public void run() {
// genTone();
handler.post(new Runnable() {
public void run() {
// genTone();
}
});
}
});
thread.start();
}
void genTone(){
// fill out the array
for (int i = 0; i < numSamples; ++i) {
sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/freqOfTone));
}
// convert to 16 bit pcm sound array
// assumes the sample buffer is normalised.
int idx = 0;
for (final double dVal : sample) {
// scale to maximum amplitude
final short val = (short) ((dVal * 32767));
// in 16 bit wav PCM, first byte is the low order byte
generatedSnd[idx++] = (byte) (val & 0x00ff);
generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
sf = (float)(val & 0x00ff);
}
}
void playSound(){
@SuppressWarnings("deprecation") //crap I know
final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT, numSamples,
AudioTrack.MODE_STATIC);
audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.play();
}
}