Android Square Wave
В настоящее время я пытаюсь сделать осциллятор, который может создавать несколько форм волны, однако мой метод прямоугольных волн генерирует ошибки, я, вероятно, делаю несколько глупых ошибок, но любая помощь будет принята. Вот мой код:
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
/**
* Created by Jack on 16/01/2017.
*/
public class PlayWave {
private final int SAMPLE_RATE = 44100; //maximum sample rate Audiotrack can use
private AudioTrack mAudio;
int buffsize = AudioTrack.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
private int sampleCount;
public PlayWave() {
mAudio = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
buffsize, AudioTrack.MODE_STATIC);
}
public void setWave (int frequency) {
sampleCount = (int) ((float) SAMPLE_RATE/frequency);
short samples[] = new short[sampleCount]; //array to hold samples
int amplitude = 32767; //
double twoPi = 8. * Math.atan(1.); //twoPi calculated as the arctangent of 1 multiplied by 8
double phase = 0.0;
for (int i = 0; i < sampleCount; i++) {
samples[i] = (short) (amplitude * Math.sin(phase));
phase += twoPi * frequency/SAMPLE_RATE;
}
mAudio.write(samples, 0, sampleCount);
}
public void setSquareWave (int frequency) {
sampleCount = (int) ((float) SAMPLE_RATE/frequency);
short samples[] = new short[sampleCount];
int amplitude = 32767;
double phase = 0.0;
double twoPi = 8. * Math.atan(1.);
for (int i = 0; i < buffsize; i++) {
short s = (amplitude * Math.sin(phase));
if (s > 0.0) {
samples[i] = 32767;
};
if (s < 0.0) {
samples[i] = -32767;
}
phase += twoPi * frequency / samples; //this loop causes errors
}
}
public void start () {
mAudio.reloadStaticData();
mAudio.setLoopPoints(0, sampleCount, -1);
mAudio.play();
}
public void stop () {
mAudio.stop();
}
}