Musical scale: Difference between revisions
Content added Content deleted
Line 898: | Line 898: | ||
<syntaxhighlight> |
<syntaxhighlight> |
||
import java.util.List; |
|||
⚫ | |||
import javax.sound.sampled.AudioFormat; |
|||
{{ out }} |
|||
import javax.sound.sampled.AudioSystem; |
|||
<pre> |
|||
import javax.sound.sampled.LineUnavailableException; |
|||
import javax.sound.sampled.SourceDataLine; |
|||
/** |
|||
</pre> |
|||
* Java can play sounds without external libraries. |
|||
*/ |
|||
public class MusicalScale { |
|||
public static void main(String[] args) throws LineUnavailableException { |
|||
List<Integer> frequencies = List.of( 262, 294, 330, 349, 392, 440, 494, 523 ); // CDEFGABC |
|||
final int duration = 500; |
|||
final int volume = 1; |
|||
for ( int i = 0; i < 3; i++ ) { |
|||
for ( int frequency : frequencies ) { |
|||
musicalTone(frequency, duration, volume); |
|||
} |
|||
} |
|||
} |
|||
private static void musicalTone(int aFrequency, int aDuration, int aVolume) throws LineUnavailableException { |
|||
byte[] buffer = new byte[1]; |
|||
AudioFormat audioFormat = getAudioFormat(); |
|||
SourceDataLine sourceDataLine = AudioSystem.getSourceDataLine(audioFormat); |
|||
sourceDataLine.open(audioFormat); |
|||
sourceDataLine.start(); |
|||
for ( int i = 0; i < aDuration * 8; i++ ) { |
|||
double angle = i / ( SAMPLE_RATE / aFrequency ) * 2 * Math.PI; |
|||
buffer[0] = (byte) ( Math.sin(angle) * 127 * aVolume ); |
|||
sourceDataLine.write(buffer, BYTE_OFFSET, buffer.length); |
|||
} |
|||
sourceDataLine.drain(); |
|||
sourceDataLine.stop(); |
|||
sourceDataLine.close(); |
|||
} |
|||
private static AudioFormat getAudioFormat() { |
|||
final int sampleSizeInBits = 8; |
|||
final int numberChannels = 1; |
|||
final boolean signedData = true; |
|||
final boolean isBigEndian = false; |
|||
return new AudioFormat(SAMPLE_RATE, sampleSizeInBits, numberChannels, signedData, isBigEndian); |
|||
} |
|||
private static float SAMPLE_RATE = 8_000.0F; |
|||
private static final int BYTE_OFFSET = 0; |
|||
} |
|||
⚫ | |||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |