Sound Demo 3
Aus ProgrammingWiki
Wiki-Quelltext dieser Seite.
<language>Java</language>
<code id="4b58377106264" hidden>
javax.sound.sampled.AudioFormat audioFormat;
javax.sound.sampled.AudioInputStream audioInputStream;
javax.sound.sampled.SourceDataLine sourceDataLine;
float sampleRate = 16000.0F;
int sampleSizeInBits = 16;
int channels = 1;
boolean signed = true;
boolean bigEndian = true;
audioData = new byte[16000*16];
void fillBuffer(double startat) {
java.nio.ByteBuffer byteBuffer;
java.nio.ShortBuffer shortBuffer;
int byteLength;
byteBuffer = java.nio.ByteBuffer.wrap(audioData);
shortBuffer = byteBuffer.asShortBuffer();
byteLength = audioData.length;
channels = 1;//Java allows 1 or 2
int bytesPerSamp = 2;
int sampLength = byteLength / bytesPerSamp;
for (int cnt = 0; cnt < sampLength; cnt++)
{
double time = cnt / sampleRate;
double sinValue = 1000*playFunction(startat+time);
shortBuffer.put((short)(sampleRate * sinValue));
}
}
void draw(int dauer, double start){
canvas.clear();
double oldy = 100;
canvas.setColor(200,200,200);
canvas.line(0,100,600,100);
canvas.setColor(0,0,0);
for(int x=0; x< 600; x++) {
double newy = 100+1000*playFunction(start+((double)dauer/2/600*x));
if(start+(double)dauer/2/600*x == 0){
canvas.setColor(200,200,200);
canvas.line(x,0,x,200);
canvas.setColor(0,0,0);
}
canvas.line(x-1,(int)(oldy),x,(int)(newy));
oldy = newy;
}
}
void play(int dauer, double startat){
audioData = new byte[16000*dauer];
try{
fillBuffer(startat);
InputStream byteArrayInputStream = new ByteArrayInputStream(audioData);
audioFormat = new javax.sound.sampled.AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
audioInputStream = new javax.sound.sampled.AudioInputStream(byteArrayInputStream, audioFormat,
audioData.length / audioFormat.getFrameSize());
javax.sound.sampled.DataLine.Info dataLineInfo =
new javax.sound.sampled.DataLine.Info(javax.sound.sampled.SourceDataLine.class, audioFormat);
sourceDataLine = (javax.sound.sampled.SourceDataLine)javax.sound.sampled.AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
playBuffer = new byte[16384];
int cnt;
while ((cnt = audioInputStream.read(playBuffer, 0,playBuffer.length))!= -1)
if (cnt > 0) sourceDataLine.write(playBuffer, 0, cnt);
sourceDataLine.drain();
sourceDataLine.stop();
sourceDataLine.close();
}
catch (Exception e){e.printStackTrace();System.exit(0);}
}
</code>
<eval id="4b58377106a33">
double playFunction(double x){
return (Math.sin((x * 3) * (x * 3)));
}
draw(8,-2); // 8 Sekunden diese Funktion spielen und mit x=-2 beginnen
play(8,-2);
</eval>
<canvas></canvas>