我创建了一个乒乓克隆,当碰撞发生时,我想添加一些声音效果。我的问题是,考虑到我的整个应用程序只有90行代码,我能找到的关于合成声音的每个示例都需要大约30行代码。我正在寻找一种更简单的方法。有没有一种简单的方法可以制造出不同音调的嘟嘟声?持续时间并不重要。我只想要一系列不同音调的嘟嘟声。
发布于 2009-12-19 18:13:29
下面是取自(缩短) Java Sound - Example: Code to generate audio tone的一个小示例
byte[] buf = new byte[ 1 ];;
AudioFormat af = new AudioFormat( (float )44100, 8, 1, true, false );
SourceDataLine sdl = AudioSystem.getSourceDataLine( af );
sdl.open();
sdl.start();
for( int i = 0; i < 1000 * (float )44100 / 1000; i++ ) {
double angle = i / ( (float )44100 / 440 ) * 2.0 * Math.PI;
buf[ 0 ] = (byte )( Math.sin( angle ) * 100 );
sdl.write( buf, 0, 1 );
}
sdl.drain();
sdl.stop();发布于 2009-12-19 18:12:00
java.awt.Toolkit.getDefaultToolkit().beep()
连续的嘟嘟声?
int numbeeps = 10;
for(int x=0;x<numbeeps;x++)
{
java.awt.Toolkit.getDefaultToolkit().beep();
}发布于 2017-12-21 08:49:52
下面是与上面相同的代码,其中包含16位的描述
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class MakeSound {
public static void main(String[] args) throws LineUnavailableException {
System.out.println("Make sound");
byte[] buf = new byte[2];
int frequency = 44100; //44100 sample points per 1 second
AudioFormat af = new AudioFormat((float) frequency, 16, 1, true, false);
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open();
sdl.start();
int durationMs = 5000;
int numberOfTimesFullSinFuncPerSec = 441; //number of times in 1sec sin function repeats
for (int i = 0; i < durationMs * (float) 44100 / 1000; i++) { //1000 ms in 1 second
float numberOfSamplesToRepresentFullSin= (float) frequency / numberOfTimesFullSinFuncPerSec;
double angle = i / (numberOfSamplesToRepresentFullSin/ 2.0) * Math.PI; // /divide with 2 since sin goes 0PI to 2PI
short a = (short) (Math.sin(angle) * 32767); //32767 - max value for sample to take (-32767 to 32767)
buf[0] = (byte) (a & 0xFF); //write 8bits ________WWWWWWWW out of 16
buf[1] = (byte) (a >> 8); //write 8bits WWWWWWWW________ out of 16
sdl.write(buf, 0, 2);
}
sdl.drain();
sdl.stop();
}
}https://stackoverflow.com/questions/1932490
复制相似问题