Musical scale: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(16 intermediate revisions by 11 users not shown)
Line 16:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE PTR="CARD"
 
PROC Wait(BYTE frames)
Line 61:
AUDCTL=$00 ;restore default configuration
Wait(20)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Musical_scale.png Screenshot from Atari 8-bit computer]
Line 74:
=={{header|AmigaBASIC}}==
 
<langsyntaxhighlight lang="amigabasic">FOR i=1 to 8
READ f
SOUND f,10
NEXT
 
DATA 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey 1.1}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">for key, val in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]
SoundBeep, % val, 500</langsyntaxhighlight>
 
=={{header|BASIC256}}==
<langsyntaxhighlight BASIC256lang="basic256">sound {261.63, 500, 293.66, 500, 329.63, 500, 349.23, 500, 392, 500, 440, 500, 493.88, 500, 523.25, 500}</langsyntaxhighlight>
 
=={{header|Befunge}}==
Line 94:
The tune to be played is specified on the first line of the code. The notes are specified as MIDI note numbers in reverse order in a Befunge string (for example, ''Middle C'' is note number 60, which is the character "<"). This is followed by the count of notes in the string - 8 in this example.
 
<langsyntaxhighlight lang="befunge">> "HGECA@><"8: v
v0*73"MThd"0006010101"MTrk"000<
>>#1-#,:#\_$8*74++,0,28*"'"039v
v,:,\,*2,1"Hd":\<,,,,,,*3"U"*9<
>"@1",2*,\,,1-:#^_"/3d",5*,,, @</langsyntaxhighlight>
 
=={{header|C}}==
Line 111:
It is therefore essential to call nosound() at the end which ends the speaker output, otherwise the Turbo C (DOS) session will have to be ended.
 
<syntaxhighlight lang="c">
<lang c>
#include<stdio.h>
#include<conio.h>
Line 138:
nosound();
return 0;
}</langsyntaxhighlight>
 
===Windows C===
Line 146:
Beep() can only play integer frequencies and thus the tones are noticeably lower than the ones played by sound() above.
 
<syntaxhighlight lang="c">
<lang c>
#include<windows.h>
#include<stdio.h>
Line 170:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
Uses Windows MIDI device
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <windows.h>
Line 248:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
{{libheader|Overtone}}
<langsyntaxhighlight lang="clojure">(use 'overtone.live)
 
; Define your desired instrument
Line 265:
(Thread/sleep ms))
 
(doseq [note (scale :c4 :major)] (play note 500))</langsyntaxhighlight>
 
=={{header|Commodore BASIC}}==
Line 272:
 
'''Commodore 64'''
<langsyntaxhighlight lang="commodorebasic">10 rem musical scale
15 rem rosetta code
20 print chr$(147)
Line 289:
90 for d=1 to 25:next
95 next i
500 data 261.63,293.66,329.63,349.23,392,440,493.88,523.25</langsyntaxhighlight>
 
'''Commodore 128'''
<langsyntaxhighlight lang="commodorebasic">10 print chr$(147)
20 play "o4 cdefgab o5 c"</langsyntaxhighlight>
 
Line 299:
=={{header|Delphi}}==
{{libheader| Winapi.Windows}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Musical_scale;
 
Line 315:
Beep(Round(note), 500);
readln;
end.</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang>n[] = [ 262 294 330 349 392 440 494 523 ]
n[] = [ 262 294 330 349 392 440 494 523 ]
for i range len n[]
for t sound [in n[i] 0.5 ]
sound [ t 0.5 ]
sleep 0.6
.
.</lang>
</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
Line 329 ⟶ 331:
 
Does not work with the Windows version of Emacs.
<langsyntaxhighlight lang="lisp">(defun play-scale (freq-list dur)
"Play a list of frequencies."
(setq header (unibyte-string ; AU header:
Line 350 ⟶ 352:
(play-sound `(sound :data ,s)))
 
(play-scale '(261.63 293.66 329.63 349.23 392.00 440.00 493.88 523.25) .5)</langsyntaxhighlight>
 
=={{header|Forth}}==
As a low level stack language Forth programming methodology prefers short simple definitions that extend the language in the direction that allows you to solve the problem. The creation of application specific language is common in Forth.
This demonstration code uses the PC speaker to generate musical tones. A simple device driver is created for hardware control via PORT I/O. A set of primitive operations are created to control the on:off times of the sounds. Then a small MUSIC language is created to create notes of different types. Finally 2 scales are created using "crotcheted notes" as they are called. We chose 1/8 notes. For fun we added the ability to change the expression of the notes using Italian musical terms.
<syntaxhighlight lang="text">HEX
\ PC speaker hardware control (requires giveio or DOSBOX for windows operation)
042 constant fctrl 061 constant sctrl
Line 444 ⟶ 446:
: Cmajor 1/8 C3 D3 E3 F3 G3 A3 B3 C4 ;
: Chromatic 1/8 C3 C#3 D3 D#3 E3 F3 F#3 G3 G#3 A3 A#3 B3 C4 ;
</syntaxhighlight>
</lang>
Interactive test at the Console
<pre>music ok
Line 454 ⟶ 456:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">REM FreeBASIC no tiene la capacidad de emitir sonido de forma nativa.
REM La función Sound no es mía, incluyo los créditos correspondientes.
' Sound Function v0.3 For DOS/Linux/Win by yetifoot
Line 526 ⟶ 528:
Sound(494, 250) 'B4
Sound(523, 250) 'C5
Sleep</langsyntaxhighlight>
=={{header|FreePascal}}==
<langsyntaxhighlight lang="pascal">{$mode objfpc}
uses windows,math;{ windows only }
var
Line 536 ⟶ 538:
for i:= 0 to 11 do
beep(Round(440.0*interval**i),500);
end.</langsyntaxhighlight>
 
=={{header|FutureBasic}}==
This code generates a fully playable 3-ocatave piano keyboard with Middle C on the eighth white key.
<syntaxhighlight lang="futurebasic">
output file "FB Piano Keyboard"
 
include "Tlbx AudioToolbox.incl"
 
_window = 1
begin enum output 1
_whiteKey01
_whiteKey02
_whiteKey03
_whiteKey04
_whiteKey05
_whiteKey06
_whiteKey07
_whiteKey08
_whiteKey09
_whiteKey10
_whiteKey11
_whiteKey12
_whiteKey13
_whiteKey14
_whiteKey15
_whiteKey16
_whiteKey17
_whiteKey18
_whiteKey19
_whiteKey20
_whiteKey21
_whiteKey22
_blackKey23
_blackKey24
_blackKey25
_blackKey26
_blackKey27
_blackKey28
_blackKey29
_blackKey30
_blackKey31
_blackKey32
_blackKey33
_blackKey34
_blackKey35
_blackKey36
_blackKey37
_infoField
_playBtn
_note01
_note02
_note03
_note04
_note05
_note06
_note07
_note08
_note09
_note10
_note11
_note12
_note13
_note14
_note15
_note16
_note17
_note18
_note19
_note20
_note21
_note22
end enum
 
begin enum output
_kMidiMessageControlChange = 0xB
_kMidiMessageProgramChange = 0xC
_kMidiMessageBankMSBControl = 0
_kMidiMessageBankLSBControl = 32
_kMidiMessageNoteOn = 0x9
end enum
 
BeginCDeclaration
AudioUnit synthUnit;
AUGraph graph;
EndC
 
void local fn PlayNote( noteNum as UInt32 )
BeginCCode
UInt8 midiChannelInUse = 0;
MusicDeviceMIDIEvent( synthUnit, kMidiMessageControlChange << 4 | midiChannelInUse, kMidiMessageBankMSBControl, 0, 0 ); //2022-Jan-04 Brian
MusicDeviceMIDIEvent( synthUnit, kMidiMessageProgramChange << 4 | midiChannelInUse, 0, 0, 0 );
AUGraphStart( graph );
UInt32 onVelocity = 127;
UInt32 noteOnCommand = kMidiMessageNoteOn << 4 | midiChannelInUse; //2022-Jan-04 Brian
MusicDeviceMIDIEvent( synthUnit, noteOnCommand, noteNum, onVelocity, 0 );
usleep ( 1 * 500 * 600 ); // 0.6 second sleep
MusicDeviceMIDIEvent( synthUnit, noteOnCommand, noteNum, 0, 0);
EndC
end fn
 
void local fn InitializeSynth
BeginCCode
AUNode synthNode, limiterNode, outNode;
AudioComponentDescription cd;
graph = 0;
synthUnit = 0;
cd.componentManufacturer = kAudioUnitManufacturer_Apple;
cd.componentFlags = 0;
cd.componentFlagsMask = 0;
NewAUGraph (&graph);
cd.componentType = kAudioUnitType_MusicDevice;
cd.componentSubType = kAudioUnitSubType_DLSSynth;
AUGraphAddNode (graph, &cd, &synthNode);
cd.componentType = kAudioUnitType_Effect;
cd.componentSubType = kAudioUnitSubType_PeakLimiter;
AUGraphAddNode (graph, &cd, &limiterNode);
cd.componentType = kAudioUnitType_Output;
cd.componentSubType = kAudioUnitSubType_DefaultOutput;
AUGraphAddNode (graph, &cd, &outNode);
AUGraphOpen (graph);
AUGraphConnectNodeInput (graph, synthNode, 0, limiterNode, 0);
AUGraphConnectNodeInput (graph, limiterNode, 0, outNode, 0);
AUGraphNodeInfo ( graph, synthNode, 0, &synthUnit );
AUGraphInitialize (graph);
EndC
end fn
 
local fn CreateKeyImage
CGRect r = {0,0,28,162}
ImageRef image = fn ImageWithSize( fn CGSizeMake( 28.0, 162.0 ) )
ImageLockFocus( image )
BezierPathFillRect( r, fn ColorBlack )
ImageUnlockFocus( image )
ImageSetName( image, @"KeyImage" )
end fn
 
void local fn BuildWindow
NSInteger i, count
NSInteger wndStyleMask = NSWindowStyleMaskTitled
wndStyleMask += NSWindowStyleMaskClosable
wndStyleMask += NSWindowStyleMaskMiniaturizable
CGRect r = {0,0,850,340}
window _window, @"FB Piano Keyboard", r, wndStyleMask
WindowSetBackgroundColor( _window, fn ColorWithRGB( 0.400, 0.400, 0.400, 1.0 ) )
// White keys
r = fn CGRectMake( 30, 30, 38, 250 )
for i = _whiteKey01 to _whiteKey22
button i,,,@"", r, NSButtonTypeMomentaryLight, NSBezelStyleTexturedSquare, _window
CALayerRef layer = fn CALayerInit
CALayerSetBackgroundColor( layer, fn ColorWithRGB( 0.800, 0.800, 0.800, 1.0 ) )
ViewSetWantsLayer( i, YES )
ViewSetLayer( i, layer )
r = fn CGRectOffset( r, 36, 0 )
next
// Black keys
r = fn CGRectMake( 52, 110, 28, 169 )
for i = _blackKey23 to _blackKey37
button i,,,@"", r, NSButtonTypeMomentaryLight, NSBezelStyleShadowlessSquare, _window
ButtonSetImageNamed( i, @"KeyImage" )
if ( i == 24 ) or ( i == 27 ) or ( i == 29 ) or ( i == 32 ) or ( i == 34 )
r = fn CGRectOffset( r, 72, 0 )
else
r = fn CGRectOffset( r, 36, 0 )
end if
next
r = fn CGRectMake( 30, 290, 240, 24 )
textfield _infoField,,,r, _window
TextFieldSetEditable( _infoField, NO )
TextFieldSetSelectable( _infoField, NO )
TextFieldSetDrawsBackground( _infoField, NO )
TextFieldSetBordered( _infoField, NO )
CFStringRef s = @"C,D,E,F,G,A,B,C,D,E,F,G,A,B,C,D,E,F,G,A,B,C"
CFArrayRef a = fn StringComponentsSeparatedByString( s, @"," )
r = fn CGRectMake( 30, 10, 38, 19 )
count = 0
for i = _note01 to _note22
textfield i,, fn ArrayObjectAtIndex( a, count ), r, _window
TextFieldSetDrawsBackground( i, NO )
TextFieldSetBordered( i, NO )
TextFieldSetEditable( i, NO )
TextFieldSetSelectable( i, NO )
TextSetAlignment( i, NSTextAlignmentCenter )
TextSetFontWithName( i, @"Menlo", 14.0 )
r = fn CGRectOffset( r, 36, 0 )
count++
next
end fn
 
local fn DoDialog( ev as NSUInteger, tag as NSUInteger, wnd as NSUInteger )
select (ev)
case _btnClick
select (tag)
case 1 : fn PlayNote( 53 ) : ControlSetStringValue( _infoField, @"C, Note 53, White key No. 1" )
case 2 : fn PlayNote( 55 ) : ControlSetStringValue( _infoField, @"D, Note 55, White key No. 2" )
case 3 : fn PlayNote( 57 ) : ControlSetStringValue( _infoField, @"E, Note 57, White key No. 3" )
case 4 : fn PlayNote( 58 ) : ControlSetStringValue( _infoField, @"F, Note 58, White key No. 4" )
case 5 : fn PlayNote( 60 ) : ControlSetStringValue( _infoField, @"G, Note 60, White key No. 5" )
case 6 : fn PlayNote( 62 ) : ControlSetStringValue( _infoField, @"A, Note 62, White key No. 6" )
case 7 : fn PlayNote( 64 ) : ControlSetStringValue( _infoField, @"B, Note 64, White key No. 7" )
case 8 : fn PlayNote( 65 ) : ControlSetStringValue( _infoField, @"C, Note 65, White key No. 8" )
case 9 : fn PlayNote( 67 ) : ControlSetStringValue( _infoField, @"D, Note 67, White key No. 9" )
case 10 : fn PlayNote( 69 ) : ControlSetStringValue( _infoField, @"E, Note 69, White key No. 10" )
case 11 : fn PlayNote( 70 ) : ControlSetStringValue( _infoField, @"F, Note 70, White key No. 11" )
case 12 : fn PlayNote( 72 ) : ControlSetStringValue( _infoField, @"G, Note 72, White key No. 12" )
case 13 : fn PlayNote( 74 ) : ControlSetStringValue( _infoField, @"A, Note 74, White key No. 13" )
case 14 : fn PlayNote( 76 ) : ControlSetStringValue( _infoField, @"B, Note 76, White key No. 14" )
case 15 : fn PlayNote( 77 ) : ControlSetStringValue( _infoField, @"C, Note 77, White key No. 15" )
case 16 : fn PlayNote( 79 ) : ControlSetStringValue( _infoField, @"D, Note 79, White key No. 16" )
case 17 : fn PlayNote( 81 ) : ControlSetStringValue( _infoField, @"E, Note 81, White key No. 17" )
case 18 : fn PlayNote( 82 ) : ControlSetStringValue( _infoField, @"F, Note 82, White key No. 18" )
case 19 : fn PlayNote( 84 ) : ControlSetStringValue( _infoField, @"G, Note 84, White key No. 19" )
case 20 : fn PlayNote( 86 ) : ControlSetStringValue( _infoField, @"A, Note 86, White key No. 20" )
case 21 : fn PlayNote( 88 ) : ControlSetStringValue( _infoField, @"B, Note 88, White key No. 21" )
case 22 : fn PlayNote( 89 ) : ControlSetStringValue( _infoField, @"C, Note 88, White key No. 22" )
case 23 : fn PlayNote( 54 ) : ControlSetStringValue( _infoField, @"C#/D\u266D, Note 54, Black key No. 23" )
case 24 : fn PlayNote( 56 ) : ControlSetStringValue( _infoField, @"D#/E\u266D, Note 56, Black key No. 24" )
case 25 : fn PlayNote( 59 ) : ControlSetStringValue( _infoField, @"F#/G\u266D, Note 59, Black key No. 25" )
case 26 : fn PlayNote( 61 ) : ControlSetStringValue( _infoField, @"G#/A\u266D, Note 61, Black key No. 26" )
case 27 : fn PlayNote( 63 ) : ControlSetStringValue( _infoField, @"A#/B\u266D, Note 63, Black key No. 27" )
case 28 : fn PlayNote( 66 ) : ControlSetStringValue( _infoField, @"C#/D\u266D, Note 66, Black key No. 28" )
case 29 : fn PlayNote( 68 ) : ControlSetStringValue( _infoField, @"D#/E\u266D, Note 68, Black key No. 29" )
case 30 : fn PlayNote( 71 ) : ControlSetStringValue( _infoField, @"F#/G\u266D, Note 71, Black key No. 30" )
case 31 : fn PlayNote( 73 ) : ControlSetStringValue( _infoField, @"G#/A\u266D, Note 73, Black key No. 31" )
case 32 : fn PlayNote( 75 ) : ControlSetStringValue( _infoField, @"A#/B\u266D, Note 75, Black key No. 32" )
case 33 : fn PlayNote( 78 ) : ControlSetStringValue( _infoField, @"C#/C\u266D, Note 78, Black key No. 33" )
case 34 : fn PlayNote( 80 ) : ControlSetStringValue( _infoField, @"D#/E\u266D, Note 80, Black key No. 34" )
case 35 : fn PlayNote( 83 ) : ControlSetStringValue( _infoField, @"F#/G\u266D, Note 83, Black key No. 35" )
case 36 : fn PlayNote( 85 ) : ControlSetStringValue( _infoField, @"G#/A\u266D, Note 85, Black key No. 36" )
case 37 : fn PlayNote( 87 ) : ControlSetStringValue( _infoField, @"A#/B\u266D, Note 87, Black key No. 37" )
end select
case _windowWillClose : end
end select
end fn
 
void local fn DoAppEvent( ev as long )
select (ev)
case _appWillFinishLaunching
fn InitializeSynth
fn CreateKeyImage
fn BuildWindow
end select
end fn
 
on appevent fn DoAppEvent
on dialog fn DoDialog
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:FB Piano Keyboard.png]]
 
 
 
=={{header|Go}}==
Line 542 ⟶ 815:
<br>
As Go doesn't have any audio support in its standard library, we instead build a .wav file which can then be played using a utility such as SoX.
<langsyntaxhighlight lang="go">package main
 
import (
Line 608 ⟶ 881:
}
}
}</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j">require'media/wav'
0.25 wavnote 0 2 4 5 7 9 11 12</langsyntaxhighlight>
 
This assumes a version such as J6 which supports media/wav.
Line 620 ⟶ 893:
 
0.25 is the duration of each note (in seconds).
 
=={{header|Java}}==
Java can play sounds without external libraries.
<syntaxhighlight lang="java">
import java.util.List;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
 
public final class MusicalScale {
 
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 );
final int duration = 500;
final int volume = 1;
for ( int i = 0; i < 3; i++ ) {
for ( double frequency : frequencies ) {
musicalTone(frequency, duration, volume);
}
}
}
private static void musicalTone(double aFrequency, int aDuration, int aVolume) {
byte[] buffer = new byte[1];
AudioFormat audioFormat = getAudioFormat();
try ( 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();
} catch (LineUnavailableException exception) {
exception.printStackTrace();
}
}
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;
 
}
</syntaxhighlight>
 
=={{header|JavaScript}}==
Using the Web Audio API
<langsyntaxhighlight lang="javascript"><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sample Page</title>
</headscript>
<body>
Upon loading the page you should hear the scale.
<script type="text/javascript">
function musicalScale(freqArr){
// create web audio api context
Line 644 ⟶ 974:
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
 
// set frequencies to play
duration = 0.5 // seconds
Line 650 ⟶ 980:
oscillator.frequency.setValueAtTime(freq, audioCtx.currentTime + i * duration);
});
 
// start playing!
oscillator.start();
Line 656 ⟶ 986:
oscillator.stop(audioCtx.currentTime + freqArr.length * duration);
}
 
musicalScale([261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]);
</script>
</head>
<body>
<button onclick="musicalScale([261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]);">Play scale</button>
</body>
</html></langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using PortAudio
 
function paudio()
Line 688 ⟶ 1,019:
sleep(0.4)
end
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 694 ⟶ 1,025:
 
When building win32.klib from windows.h, one needs to make sure NOT to filter out utilapiset.h because this is where the Beep function now resides, not in winbase.h as stated in the MSDN documentation.
<langsyntaxhighlight lang="scala">// Kotlin Native v0.3
 
import kotlinx.cinterop.*
Line 703 ⟶ 1,034:
val dur = 500
repeat(5) { for (freq in freqs) Beep(freq, dur) }
}</langsyntaxhighlight>
 
=={{header|Lilypond}}==
The lilypond tool produces musical score sheets and midi files - if asked for - but does not output notes to the sound device directly.
<langsyntaxhighlight lang="lilypond">% Start at middle C
\relative c' {
c d e f
g a b c
}</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="Scheme">
 
Using the musicalScale() javascript function found in this wiki page, we build a lambdatalk interface to output the 8 notes of the C major diatonic scale, and more.
 
{def note
{lambda {:i}
{round {* 261.63 {pow 2 {/ :i 12}}}}}}
 
{def scale
{lambda {:notes}
[{S.map {lambda {:i} {note :i},} :notes}]}}
 
{def play
{lambda {:n}
{input {@ type="button"
value="Play :n"
onclick="musicalScale({scale :n});"}}}}
 
1) diatonic up
{play 0 2 4 5 7 9 11 12}
 
2) diatonic down
{play 12 11 9 7 5 4 2 0}
 
3) twelve notes of the octave plus one
{play {S.serie 0 12}}
4) one more ... from Fantasia (Disney Studios, 1940)
{play 0 2 3 5 7 3 7 7 6 2 6 6 7 3 7 7 0 2 3 5 7 3 7 12 10 7 3 7 10 10 10 10}
->
</syntaxhighlight>
 
=={{header|Locomotive Basic}}==
 
<langsyntaxhighlight lang="locobasic">10 mode 1
20 print "Note","Freq. (Hz)","Period"
30 ' program loop:
Line 730 ⟶ 1,094:
140 sound 1,p,100
150 return
160 data 1,3,5,6,8,10,12,13,-1</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 736 ⟶ 1,100:
===Lua Portable===
The most portable native solution that could actually ''play'' the scale (''with some external help from a media player'') would be to write a MIDI file..
<langsyntaxhighlight lang="lua">c = string.char
midi = "MThd" .. c(0,0,0,6,0,0,0,1,0,96) -- header
midi = midi .. "MTrk" .. c(0,0,0,8*8+4) -- track
Line 749 ⟶ 1,113:
 
-- (optional: hex dump to screen)
midi:gsub(".", function(c) io.write(string.format("%02X ", string.byte(c))) end)</langsyntaxhighlight>
{{out}}
<pre>4D 54 68 64 00 00 00 06 00 00 00 01 00 60 4D 54 72 6B 00 00 00 44 00 90 3C 40 60 80 3C 00 00 90 3E 40 60 80 3E 00 00 90 40 40 60 80 40 00 00 90 41 40 60 80 41 00 00 90 43 40 60 80 43 00 00 90 45 40 60 80 45 00 00 90 47 40 60 80 47 00 00 90 48 40 60 80 48 00 00 FF 2F 00</pre>
Line 755 ⟶ 1,119:
===Lua ASCII===
The task allows for score output, which could also be done natively..
<langsyntaxhighlight lang="lua">staff = {
lines = { "", "", "", "", "", "", "", "", "", "", "" },
nnotes = 0,
Line 781 ⟶ 1,145:
end
staff:measure()
staff:dump()</langsyntaxhighlight>
{{out}}
<pre>|----------------|----------------|
Line 797 ⟶ 1,161:
===Lua Windows===
Non-portable, O/S-specific, requires <code>alien</code> library..
<langsyntaxhighlight lang="lua">beep = require"alien".kernel32.Beep
beep:types{ret='long', abi='stdcall', 'long', 'long'}
for _,step in ipairs{0,2,4,5,7,9,11,12} do
beep(math.floor(261.63 * 2^(step/12) + 0.5), 1000)
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 809 ⟶ 1,173:
TUNE use kernel [https://msdn.microsoft.com/en-us/library/windows/desktop/ms679277(v=vs.85).aspx Beep] which is synchronous and not leaving M2000 threads to process, until ends.
 
<syntaxhighlight lang="text">
Module checkit {
\\ using internal speaker
Line 824 ⟶ 1,188:
}
checkit
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">EmitSound@Sound[SoundNote /@ {0, 2, 4, 5, 7, 9, 11, 12}]</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight lang="nanoquery">import tonegen
 
note_freqs = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}
Line 837 ⟶ 1,201:
for freq in note_freqs
tg.beep(freq)
end</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Go}}
<langsyntaxhighlight Nimlang="nim">import endians, math
 
const
Line 892 ⟶ 1,256:
file.write chr(y.byte) # Signed int to byte then to char as it’s easier this way.
 
file.close()</langsyntaxhighlight>
 
=={{header|ooRexx}}==
<langsyntaxhighlight ooRexxlang="oorexx">/* REXX ---------------------------------------------------------------
* 24.02.2013 Walter Pachl derived from original REXX version
* Changes: sound(f,sec) --> beep(trunc(f),millisec)
Line 928 ⟶ 1,292:
If f.note\==0 Then
Call beep trunc(f.note),dur /* sound the "note". */
Return</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use MIDI::Simple;
 
# setup, 1 quarter note is 0.5 seconds (500,000 microseconds)
Line 939 ⟶ 1,303:
n 60; n 62; n 64; n 65; n 67; n 69; n 71; n 72;
 
write_score 'scale.mid';</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
=== version 1 ===
{{libheader|Phix/online}}
{{trans|Scala}}
You can run this online [http://phix.x10.mx/p2js/Musical_scale.htm here].
{{trans|Raku}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>atom xBeep = 0
<span style="color: #000080;font-style:italic;">--
 
-- demo\rosetta\Musical_scale.exw
procedure beep(integer fi)
--</span>
if platform()=WINDOWS then
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer frequency = floor(261.63 * power(2, fi/12)),
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
duration = iff(fi == 12 ? 1000 : 500)
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #7060A8;">beep</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
if xBeep=0 then
atom kernel32 = open_dll("kernel32.dll")
xBeep = define_c_proc(kernel32, "Beep", {C_INT,C_INT})
end if
c_proc(xBeep,{frequency,duration})
elsif platform()=LINUX then
string play = sprintf("play -n -c1 synth 0.2 sin %%%d",fi-9)
system(play)
end if
end procedure
 
printf(1,"Please don't shoot the piano player, he's doing the best that he can!\n")
constant f = {0, 2, 4, 5, 7, 9, 11, 12}
for i=1 to length(f) do
beep(f[i])
end for
printf(1,"That's all\n")</lang>
=== version 2 ===
{{trans|Sparkling}}
{{trans|Go}}
<lang Phix>constant sample_rate = 44100,
duration = 8,
dataLength = sample_rate * duration,
hdrSize = 44,
fileLen = dataLength + hdrSize - 8,
freqs = { 261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3 },
wavhdr = "RIFF"&
int_to_bytes(fileLen,4)&
"WAVE"&
"fmt "&
int_to_bytes(16,4)& -- length of format data (= 16)
int_to_bytes(1,2)& -- type of format (= 1 (PCM))
int_to_bytes(1,2)& -- number of channels (= 1)
int_to_bytes(sample_rate,4)& -- sample rate
int_to_bytes(sample_rate,4)& -- sample rate * bps(8) * channels(1) / 8 (= sample rate)
int_to_bytes(1,2)& -- bps(8) * channels(1) / 8 (= 1)
int_to_bytes(8,2)& -- bits per sample (bps) (= 8)
"data"&
int_to_bytes(dataLength,4) -- size of data section
if length(wavhdr)!=hdrSize then ?9/0 end if -- sanity check
<span style="color: #008080;">constant</span> <span style="color: #000000;">freq</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">261.63</span><span style="color: #0000FF;">,</span><span style="color: #000000;">293.66</span><span style="color: #0000FF;">,</span><span style="color: #000000;">329.63</span><span style="color: #0000FF;">,</span><span style="color: #000000;">349.23</span><span style="color: #0000FF;">,</span><span style="color: #000000;">392</span><span style="color: #0000FF;">,</span><span style="color: #000000;">440</span><span style="color: #0000FF;">,</span><span style="color: #000000;">493.88</span><span style="color: #0000FF;">,</span><span style="color: #000000;">523.25</span><span style="color: #0000FF;">},</span>
integer fn = open("notes.wav", "wb")
<span style="color: #000000;">durations</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">500</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">freq</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">&</span> <span style="color: #000000;">1000</span>
puts(fn, wavhdr)
for j=1 to duration do
<span style="color: #008080;">function</span> <span style="color: #000000;">button_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*playbtn*/</span><span style="color: #0000FF;">)</span>
atom omega = 2 * PI * freqs[j]
<span style="color: #7060A8;">beep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">freq</span><span style="color: #0000FF;">,</span><span style="color: #000000;">durations</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">)</span>
for i=0 to dataLength/duration-1 do
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
atom y = 32 * sin(omega * i / sample_rate)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
integer byte = and_bits(y,#FF)
puts(fn,byte)
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
end for
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">label</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Please don't shoot the piano player, he's doing the best that he can!"</span><span style="color: #0000FF;">),</span>
end for
<span style="color: #000000;">playbtn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Play"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"button_cb"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"PADDING=30x0"</span><span style="color: #0000FF;">),</span>
close(fn)
<span style="color: #000000;">hbox</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupFill</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">playbtn</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">IupFill</span><span style="color: #0000FF;">()},</span><span style="color: #008000;">"MARGIN=0x20"</span><span style="color: #0000FF;">),</span>
 
<span style="color: #000000;">vbox</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">label</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hbox</span><span style="color: #0000FF;">},</span> <span style="color: #008000;">"MARGIN=10x5, GAP=5"</span><span style="color: #0000FF;">),</span>
if platform()=WINDOWS then
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">vbox</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`TITLE="Musical Scale"`</span><span style="color: #0000FF;">)</span>
system("notes.wav")
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
elsif platform()=LINUX then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
system("aplay notes.wav")
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
end if</lang>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
=={{header|PowerShell}}==
List of frequencies directly taken from the Python example.
<langsyntaxhighlight lang="powershell">$frequencies = 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25
foreach($tone in $frequencies){
[Console]::beep($tone, 500)
}</langsyntaxhighlight>
 
=={{header|Processing}}==
Requires the Processing Sound library.
 
<syntaxhighlight lang="java">
//Aamrun, 2nd July 2022
 
import processing.sound.*;
 
float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};
 
SinOsc sine;
 
size(500,500);
 
sine = new SinOsc(this);
 
for(int i=0;i<frequencies.length;i++){
sine.freq(frequencies[i]);
sine.play();
 
delay(500);
}
</syntaxhighlight>
 
=={{header|Pure Data}}==
Line 1,082 ⟶ 1,434:
=={{header|Python}}==
(Windows)
<langsyntaxhighlight lang="python">>>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
winsound.Beep(int(note+.5), 500)
>>> </langsyntaxhighlight>
 
'''Library:''' SDL2 (pip install PySDL2)
 
<syntaxhighlight lang="python">
import sys
import ctypes
import math
import time
import struct
import sdl2
import sdl2.sdlmixer as mixer
 
 
def create_sound(frequency, duration):
"""Create a buffer with sound at given frequency and duration"""
num_samples = int(48000 * duration)
wave = struct.pack(
f"<{num_samples}i",
*[
int(2**30 * math.sin(2 * math.pi * frequency / 48000 * t))
for t in range(num_samples)
]
)
length = num_samples * 4
sound_buffer = (ctypes.c_ubyte * length).from_buffer_copy(wave)
sound = mixer.Mix_QuickLoad_RAW(
ctypes.cast(sound_buffer, ctypes.POINTER(ctypes.c_ubyte)), length
)
return sound
 
 
def main():
"""Play sine wave"""
mixer.Mix_Init(0)
 
mixer.Mix_OpenAudioDevice(48000, sdl2.AUDIO_S32, 1, 2048, None, 0)
 
note = 261.63
semitone = math.pow(2, 1 / 12)
duration = 0.5 # seconds
 
for step in [0, 2, 2, 1, 2, 2, 2, 1]:
note *= semitone**step
sound = create_sound(note, duration)
mixer.Mix_PlayChannel(0, sound, 1)
time.sleep(duration)
 
return 0
 
 
if __name__ == "__main__":
sys.exit(main())
 
</syntaxhighlight>
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
install.packages("audio")
library(audio)
Line 1,096 ⟶ 1,502:
Sys.sleep(.7)
}
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
With a quick and dirty WinMM interface.
<langsyntaxhighlight lang="racket">
#lang racket
(require ffi/unsafe ffi/unsafe/define)
Line 1,112 ⟶ 1,518:
(for ([i '(60 62 64 65 67 69 71 72)]) (midi #x90 i 127) (sleep 0.5))
(sleep 2)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>for 0,2,4,5,7,9,11,12 {
shell "play -n -c1 synth 0.2 sin %{$_ - 9}"
}</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 1,124 ⟶ 1,530:
{{works with|Personal REXX}}
{{works with|Regina}}
<langsyntaxhighlight lang="rexx">/*REXX program sounds eight notes of the C major natural diatonic music scale.*/
parse arg ! /*obtain optional arguments from the CL*/
/* [↓] invoke boilerplate REXX code. */
Line 1,161 ⟶ 1,567:
!rex: parse upper version !ver !vernum !verdate .; !brexx= 'BY'==!vernum; !kexx= "KEXX"==!ver; !pcrexx= 'REXX/PERSONAL'==!ver | "REXX/PC"==!ver; !r4= 'REXX-R4'==!ver; !regina= "REXX-REGINA"==left(!ver, 11); !roo= 'REXX-ROO'==!ver; call !env; return
!sys: !cms= !sys=='CMS'; !os2= !sys=="OS2"; !tso= !sys=='TSO' | !sys=="MVS"; !vse= !sys=='VSE'; !dos= pos("DOS", !sys)\==0 | pos('WIN', !sys)\==0 | !sys=="CMD"; !crx= left(!sys, 6)=='DOSCRX'; call !rex; return
!var: call !fid; if !kexx then return space( dosenv( arg(1) ) ); return space( value( arg(1), , !env) )</langsyntaxhighlight>
 
Programming note: &nbsp;
Line 1,183 ⟶ 1,589:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Musical scale
 
Line 1,192 ⟶ 1,598:
beep(freqs[f][1],300)
next
</syntaxhighlight>
</lang>
Output video:
 
[https://www.dropbox.com/s/jf34s6apalw0k7c/CalmoSoftMusicalScale.avi?dl=0 Musical scale]
 
=={{header|RPL}}==
≪ 2 SWAP 12 / ^ 440 * ≫ '<span style="color:blue>FREQ</span>' STO
≪ { -9 -7 -5 -4 -2 0 2 3 }
1 OVER SIZE '''FOR''' j
DUP j GET <span style="color:blue>FREQ</span> .1 BEEP '''NEXT'''
DROP
≫ '<span style="color:blue>GAMME</span>' STO
 
=={{header|Scala}}==
===Windows===
{{libheader|net.java.dev.sna.SNA}}
<langsyntaxhighlight Scalalang="scala">import net.java.dev.sna.SNA
 
object PlayMusicScale extends App with SNA {
Line 1,211 ⟶ 1,626:
foreach(f => Beep((261.63 * math.pow(2, f / 12.0)).toInt, if (f == 12) 1000 else 500))
println("That's all")
}</langsyntaxhighlight>
 
=={{header|Sparkling}}==
The following Sparkling program generates a WAVE audio file named "notes.wav"
that can be played in order to achieve the required effect:
<langsyntaxhighlight Sparklinglang="sparkling">var sampleRate = 44100.0;
var duration = 8.0;
var dataLength = round(sampleRate * duration);
Line 1,265 ⟶ 1,680:
}
 
fclose(f);</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{libheader|Snack}}
<langsyntaxhighlight lang="tcl">package require sound
 
# Encapsulate the tone generation
Line 1,291 ⟶ 1,706:
foreach i {0 2 4 5 7 9 11 12 11 9 7 5 4 2 0} {
play [expr {$tonicFrequency*2**($i/12.0)}] [expr {$i%12?250:500}]
}</langsyntaxhighlight>
 
=={{header|Ursa}}==
{{trans|Python}}
<langsyntaxhighlight lang="ursa">decl double<> notes
append 261.63 293.66 329.63 349.23 392.00 440.00 493.88 523.25 notes
 
for (decl int i) (< i (size notes)) (inc i)
ursa.util.sound.beep notes<i> 0.5
end for</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long
Line 1,313 ⟶ 1,728:
Beep Fqs(i), 500
Next
End Sub</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<br>
As Vlang doesn't have any audio support in its standard library, we instead build a .wav file which can then be played using a utility such as SoX.
<syntaxhighlight lang="v (vlang)">import strings
import os
import encoding.binary
Line 1,379 ⟶ 1,794:
}
}
}</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 1,385 ⟶ 1,800:
{{libheader|Wren-sound}}
As Wren-cli doesn't have any built-in audio support, we instead build a .wav file which can then be played using a utility such as rhythmbox or SoX.
<langsyntaxhighlight ecmascriptlang="wren">import "./sound" for Wav
 
var sampleRate = 44100
Line 1,399 ⟶ 1,814:
}
}
Wav.create("musical_scale.wav", data, sampleRate)</langsyntaxhighlight>
<br>
It's also possible to play .wav files which (preferably) have a sample rate of 44.1 kHz using DOME:
{{libheader|DOME}}
<langsyntaxhighlight ecmascriptlang="wren">import "audio" for AudioEngine
 
class Main {
Line 1,418 ⟶ 1,833:
}
 
var Game = Main.new()</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">\Square waves on the beeper speaker:
code Sound=39;
real Period; int I;
Line 1,441 ⟶ 1,856:
Note:= Note + (if I&3 then 2 else 1);
];
]</langsyntaxhighlight>
 
=={{header|Yabasic}}==
{{trans|Phix}}
<langsyntaxhighlight Yabasiclang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Musical_scale
// by Galileo, 03/2022
 
Line 1,498 ⟶ 1,913:
else // Linux
system("aplay notesyab.wav")
endif</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 REM Musical scale
20 LET n=0: REM Start at middle C
30 LET d=0.2: REM Make each note 0.2 seconds in duration
Line 1,510 ⟶ 1,925:
80 NEXT l
90 STOP
9000 DATA 2,2,1,2,2,2,1,2:REM WWHWWWH</langsyntaxhighlight>
9,476

edits