Skip to content

Instantly share code, notes, and snippets.

@bonar bonar/SinWave.java
Created Apr 19, 2009

Embed
What would you like to do?
import java.lang.Math;
import java.util.Vector;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
public class SinWave {
private static final float SAMPLE_RATE = 44100.0f;
private static final int SAMPLE_SIZE = 16;
private static final int CHANNEL = 2;
private static final int FRAME_SIZE = 2;
private static final float FRAME_RATE = 44100.0f;
private static final int VOLUME = 50;
public static void main (final String[] arg)
throws IOException {
Vector<Float> freqs = new Vector<Float>();
for (int i = 0; i < arg.length; i++) {
freqs.add(Float.valueOf(arg[i]));
}
int buffsize = ((int)SAMPLE_RATE * CHANNEL);
byte[] buff = new byte[(buffsize * freqs.size())];
int cursor = 0;
for (Float freq : freqs) {
// SAMPLE_RATE 内で target_hz 個の波形を入れる必要が
// あるため、一回の波形に割り当てるサンプル数は
// (SAMPLE_RATE / target_hz) になる。
float target_freq = freq.floatValue();
int samples_per_round = (int)(SAMPLE_RATE / target_freq);
// target_freq 回波形を書く
for (int i = 0; i < (int)target_freq; i++) {
// 1回の波形を samples_per_round の点に分けて書く
for (int x = 0; x < samples_per_round; x++) {
float progress = ((float)x / samples_per_round);
double radian = progress * (2 * Math.PI);
byte y = (byte)(Math.sin(radian) * VOLUME);
buff[cursor++] = y; // Left
buff[cursor++] = y; // Right
}
}
}
// WAVE ファイルとして出力
AudioFormat fmt = new AudioFormat(
// AudioFormat.Encoding encoding
AudioFormat.Encoding.PCM_SIGNED,
SAMPLE_RATE, // sampleRate
SAMPLE_SIZE, // sampleSizeInBits
CHANNEL, // channels
FRAME_SIZE, // frameSize
FRAME_RATE, // frameRate
true //int bigEndian
);
AudioInputStream audio_stream = new AudioInputStream(
new ByteArrayInputStream(buff), fmt, cursor);
File outfile = new File("sinwave.wav");
AudioSystem.write(audio_stream
, AudioFileFormat.Type.WAVE, outfile);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.