Musical scale: Difference between revisions
Content added Content deleted
(add RPL) |
|||
Line 907: | Line 907: | ||
* Java can play sounds without external libraries. |
* Java can play sounds without external libraries. |
||
*/ |
*/ |
||
public class MusicalScale { |
public final class MusicalScale { |
||
public static void main(String[] |
public static void main(String[] aArgs) { |
||
List<Double> frequencies = List.of( 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25 ); |
List<Double> frequencies = List.of( 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25 ); |
||
final int duration = 500; |
final int duration = 500; |
||
Line 921: | Line 921: | ||
} |
} |
||
private static void musicalTone(double aFrequency, int aDuration, int aVolume) |
private static void musicalTone(double aFrequency, int aDuration, int aVolume) { |
||
byte[] buffer = new byte[1]; |
byte[] buffer = new byte[1]; |
||
AudioFormat audioFormat = getAudioFormat(); |
AudioFormat audioFormat = getAudioFormat(); |
||
try ( SourceDataLine sourceDataLine = AudioSystem.getSourceDataLine(audioFormat) ) { |
|||
sourceDataLine.open(audioFormat); |
sourceDataLine.open(audioFormat); |
||
sourceDataLine.start(); |
sourceDataLine.start(); |
||
for ( int i = 0; i < aDuration * 8; i++ ) { |
for ( int i = 0; i < aDuration * 8; i++ ) { |
||
double angle = i / ( SAMPLE_RATE / aFrequency ) * 2 * Math.PI; |
double angle = i / ( SAMPLE_RATE / aFrequency ) * 2 * Math.PI; |
||
buffer[0] = (byte) ( Math.sin(angle) * 127 * aVolume ); |
buffer[0] = (byte) ( Math.sin(angle) * 127 * aVolume ); |
||
sourceDataLine.write(buffer, BYTE_OFFSET, buffer.length); |
sourceDataLine.write(buffer, BYTE_OFFSET, buffer.length); |
||
} |
} |
||
sourceDataLine.drain(); |
sourceDataLine.drain(); |
||
sourceDataLine.stop(); |
sourceDataLine.stop(); |
||
sourceDataLine.close(); |
sourceDataLine.close(); |
||
} catch (LineUnavailableException exception) { |
|||
exception.printStackTrace(); |
|||
} |
|||
} |
} |
||