Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Write a program to play the popular English nursery rhyme.

Sheet music (This file is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported license. Attribution: Helix84 at the English language Wikipedia; Blahedo at the English language Wikipedia.)

Some Wikipedia articles that may be useful:

Some guidelines for your submission:

  • Your program must use the computer's sound card. If your programming language doesn't have convenient access to audio hardware, your program must create an output file in some standard format such as WAV or MIDI.

  • Your program must actually generate its output. For example, embedding the Ogg Vorbis file from Wikipedia would not be allowed.

  • The audio quality must be acceptable. At the very least, the song should be easily recognizable. Preferably, it should sound good as well.

  • The focus should be on code size, sound quality, or both (explain which one you decided on). Elegant solutions would also be great. Have fun!

share|improve this question

closed as off-topic by Eᴀsᴛᴇʀʟʏ Iʀᴋ, Martin Ender Mar 20 at 16:07

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions without an objective primary winning criterion are off-topic, as they make it impossible to indisputably decide which entry should win." – Eᴀsᴛᴇʀʟʏ Iʀᴋ, Martin Ender
If this question can be reworded to fit the rules in the help center, please edit the question.

Why no midi? Is it really simpler to implement a midi file than to dump a sine wave to hardware? – mootinator Jan 31 '11 at 4:28
@mootinator: Good point. I would also like to see a variety of submissions, so I am removing the "no MIDI" rule. – PleaseStand Jan 31 '11 at 11:53
can I approximate note frequencies? – Ming-Tang May 20 '11 at 4:06

12 Answers 12

up vote 26 down vote accepted

QBasic (56)

PLAY "L4"+A$+B$+B$+A$

Focus is on reminiscence :)

(Don't have a QBasic to test this though)

share|improve this answer
Works on my DOSBox installation at least, but could you modify it to play the full song? – PleaseStand Jan 31 '11 at 11:49
Done. I'll go work on my reading skills :/ – Eelvex Jan 31 '11 at 11:57
Hmm is this page wrong? -- >An octave begins with C and ends with B. I did half expect QBASIC to be middle C based, but that notation would suggest it's A220 based if exactly correct :) – mootinator Jan 31 '11 at 15:35
Wow, this brings back memories of my first programming experiences with QBasic...which involved, among other things, writing cheesy music! – Daniel Standage Jan 31 '11 at 16:40
+1 for trip down memory lane! Now all I need is a DRAW command sample :) – System Down May 20 '11 at 21:32

JavaScript (214 212 211 characters)

Open Safari, Opera, or Google Chrome to JavaScript Shell, then enter the code below:

for(s="",y=192e3;x=--y/4e3|0;)s+="~ "[(y%4e3>800|x%8==1)&Math.pow(2,"024579702457245702457970"[x>>1]/12)*y/31%2];open("data:audio/wav;base64,UklGRiXuAgBXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQHuAgCA"+btoa(s))

Unminified for readability (even then it may be hard to understand):

for(s = "", y = 192E3; x = --y / 4E3 | 0;) {
  s += "~ "[(y % 4E3 > 800 | x % 8 == 1) & Math.pow(2, "024579702457245702457970"[x >> 1] / 12) * y / 31 % 2];
open("data:audio/wav;base64,UklGRiXuAgBXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQHuAgCA" + btoa(s));

With several more characters, it could work on Firefox as well, but you can change the audio/wav part to at least save the WAV file.

share|improve this answer
Works just fine in Chrome. – mootinator Jan 31 '11 at 23:19
@mootinator: Works for me as well. I hadn't thought of checking it in Chrome -- it had not gained WAV file support until fairly recently. – PleaseStand Jan 31 '11 at 23:42
Wow! This is wonderful. – Phillip Senn May 19 '11 at 22:00
what do you mean by "with several more characters"? What would those characters be? – Phillip Senn May 19 '11 at 22:02
@cf_PhillipSenn: When I ran the code on Firefox, I got a non-functional QuickTime Player. I had to change the code open(...) to Audio(...).play() (8 more characters) to get it to use Firefox's working built-in audio player. – PleaseStand May 20 '11 at 2:19

C# (Length: LOL)

So, what I did here was implement support for generating a .wav file from the string used for the QBasic solution in C# (single octave, no accidentals). Emphasis was on:

  1. Avoiding unsafe code blocks
  2. Not wasting too much of my time doing it
  3. Making it relatively simple to extend

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.IO;

namespace ConsoleApplication1
    public static class Extension
        public static byte[] ToByteArray(this object o)
            return o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .SelectMany(x =>
                                    var value = x.GetValue(o, null);
                                    if (value.GetType().Equals(typeof (UInt16)))
                                        return BitConverter.GetBytes((UInt16) value);
                                    if (value.GetType().Equals(typeof (UInt32)))
                                        return BitConverter.GetBytes((UInt32) value);
                                    if (value.GetType().Equals(typeof(char[])))
                                        return ((char[]) value).Select(y => Convert.ToByte(y));
                                    if (value.GetType().Equals(typeof(byte[])))
                                        return (byte[]) value;
                                    throw new NotImplementedException();
    public class Wave
        public readonly byte[] WavFile; 

        public Wave(string notes)
            var header = new Header();
            var data = new List<Chunk>();
            var f = new Fmt(8000);
            data.Add(new WavData(notes, f));
            var thefile = data.SelectMany(x => x.ToByteArray()).ToArray();
            header.Size = (uint)thefile.Length + 4;
            WavFile = header.ToByteArray().Concat(thefile).ToArray();
        class WavData: Chunk
            private static IEnumerable<byte> RenderNote(string note, int length, Fmt fmt)
                double frequency;
                switch (note)
                    case "A":
                        frequency = 440;
                    case "B":
                        frequency = 493.883;
                    case "C":
                        frequency = 261.626;
                    case "D":
                        frequency = 293.665;
                    case "E":
                        frequency = 329.628;
                    case "F":
                        frequency = 349.228;
                    case "G":
                        frequency = 391.995;
                        throw new NotImplementedException("Unsupported Note");
                var result = new byte[fmt.SampleRate / length * 2];  // For 120BPM tempo
                for (int i = 0; i < result.Length; i++)
                    double time = (i % fmt.SampleRate) / (double)fmt.SampleRate;
                    double position = time * frequency;
                    if (result.Length - i <= fmt.SampleRate / 16)
                        result[i] = 127;
                        result[i] = (byte)Math.Round((Math.Sin(position * 2 * Math.PI) + 1) * 127);
                return result;
            public WavData(string notes, Fmt fmt)
                Samples = new byte[0];
                foreach (var note in Regex.Matches(notes, @"[A-G][1|2|4|8]?").OfType<Match>().Select(x => x.Value))
                    Samples = Samples.Concat(RenderNote(note[0] + "", note.Length > 1 ? note[1] - '0' : 4, fmt)).ToArray();

            public override char[] Id
                get { return "data".ToCharArray(); }
            public override uint DataSize
                get { return (uint)Samples.Length; }
            public byte[] Samples { get; private set; }
        class Fmt : Chunk
            public Fmt(UInt32 sampleRate)
                CompressionCode = 1; // Unknown/PCM
                Channels = 1;
                SampleRate = sampleRate;
                SignificantBits = 8;
            public override char[] Id
                get { return "fmt ".ToCharArray();}
            public override uint DataSize
                get { return 16; }
            public UInt16 CompressionCode { get; private set; }
            public UInt16 Channels { get; private set; }
            public UInt32 SampleRate { get; private set; }
            public UInt32 AvgBytesPerSecond { get { return SampleRate*BlockAlign; } }
            public UInt16 BlockAlign { get { return (UInt16) (SignificantBits/8*Channels); } }
            public UInt16 SignificantBits { get; private set; }
        class Header
            public Header()
                Type = "RIFF".ToCharArray();
                RiffType = "WAVE".ToCharArray();
                Size = 0;

            public char[] Type { get; private set; }
            public UInt32 Size { get; set; }
            public char[] RiffType { get; private set; }
        abstract class Chunk
            public abstract char[] Id { get; }
            public abstract UInt32 DataSize { get; }
    class Program
        public static void Main(string[] args)
            var p1 = "CCGGAAG2";
            var p2 = "FFEEDDC2";
            var p3 = "GGFFEED2";
            var w = new Wave(p1+p2+p3+p3+p1+p2);
            using (var f = new FileStream("testfile.wav", FileMode.Create))
                f.Write(w.WavFile, 0, w.WavFile.Length);
share|improve this answer
I noticed the output wave has a very small amplitude in my answer above. Clearly I'm missing something about how an 8 bit sample works. – mootinator Mar 9 '11 at 15:58
Ah, fixed it. Order of operations is important. Sample output here: – mootinator Mar 9 '11 at 16:17
FromDigits["LOL",36]==28101 That does not look like LOL<sub>36</sub> bytes... – CalculatorFeline Mar 11 at 15:15

Python (259)

import pysynth



share|improve this answer
couldn't this be shortened to import ttls? – zzzzBov Mar 11 '11 at 20:38
@zzz: Um, is that a joke? – John Mar 11 '11 at 20:48
no more than this is sarcasm. – zzzzBov Mar 11 '11 at 20:51
@zzz: -Bangs-head-on-desk- What are you saying exactly? – John Mar 11 '11 at 20:54
@John it's obviously a koan. you should either bow or hit him. – ixtmixilix Sep 9 '11 at 8:41

C, 277 characters

a[]={0,7,9,7,5,4,2,0,7,5,4,2,7,5,4,2,0,7,9,7,5,4,2,0},i,j,f;main(){unsigned char

Perl, 203 characters

open F,'>:raw','/dev/dsp';for$a(0,7,9,17,5,4,2,10,7,5,4,12,7,5,4,12,0,7,9,17,5,4
,2,10){$b=pack'C*',map 127*($a>9||$_/400%20!=9?1+sin($_*2**($a%10/12)):1),0..
7999;$b=substr$b,syswrite F,$b while length$b}

Conveniently, OSS's /dev/dsp defaults to 8kHz mono u8; all I do here is open the device and write computed samples.

share|improve this answer
Post Perl separately; you're on codegolf :) – Eelvex Nov 2 '11 at 3:10

C - 520


#include <linux/fd.h>
#include <time.h>
struct timespec t,p;char*q="AAHHJJH  FFEECCA  HHFFEEC  HHFFEEC  AAHHJJH  FFEECCA";x,y,z,v,w;main(){x=open("/dev/fd0",3);for(y;q[y];y++){clock_gettime(CLOCK_MONOTONIC,&p);if(q[y]>' ')for(w=z=0;z<4e8;z+=t.tv_nsec,w++){struct floppy_raw_cmd s={0};s.flags=FD_RAW_NEED_SEEK;v=!v;s.track=v;ioctl(x,FDRAWCMD,&s);clock_gettime(CLOCK_MONOTONIC,&t);t.tv_nsec=(w+1)*5e8/pow(2.,q[y]/12.)-(t.tv_sec-p.tv_sec)*1e9-t.tv_nsec+p.tv_nsec;t.tv_sec=0;nanosleep(&t,0);}t.tv_nsec=2e8;nanosleep(&t,0);}}

Why use past century's hardware like speakers and headphones? This excellent piece of code lets you play the song on a modern piece of hardware: a floppy drive!
No special requirements:

  • An IDE floppy drive
  • Linux kernel
  • Compile with -lm
  • Make sure the program can access /dev/fd0, so either chown the device or run as superuser

Bends the rules a bit, but let's for a second consider the floppy drive a sound device, and the IDE controller an integrated sound card.

share|improve this answer
I'd say this is reasonable, floppy drives are surprisingly capable for this task – LockOpeners Mar 11 at 17:37

HyperCard 2.2 - 113

play harpsichord "c c g g a a gh fq f e e d d ch gq g f f e e dh gq g f f e e dh cq c g g a a gh fq f e e d d ch"

Usage: Start HyperCard, type ⌘M to open the Message Box, paste the code above, and press enter.

harpsichord may be replaced with flute or boing to get different sounds.

share|improve this answer
(very late comment) harpsichord -> flute -6 remove the space between instrument and quotes -1 total -7 – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ Jun 20 at 17:25

C, 96 chars


Produces raw 8-bit unsigned mono audio data in classic bytebeat style. Recommended sample rates for playback are between 8 and 16 kHz; changing the sample rate changes the tempo and pitch.

To compile and play under Linux, save the code above as twinkle.c and run the following commands:

gcc twinkle.c -o twinkle
./twinkle | aplay

Some notes on how the code works:

  • The general trick used for bytebeat compositions like this is that putchar() takes an integer value but only prints the low eight bits of it. Thus, putchar(t), where t is an increasing counter, generates a sawtooth wave, and the frequency of the wave can be altered by multiplying t with a suitable value.

  • !!(t>>9&7|!(-t>>12&7)) produces the repeating 6+1 note pattern. Specifically, !!(t>>9&7) evaluates to 0 whenever t>>9 & 7 == 0 and to 1 otherwise. Thus, it produces a 512-sample gap in the waveform every 4096 samples, while the !(-t>>12&7) eliminates every eighth such gap.

  • 96+"#d|dOE3#dOE3dOE3"[t>>13&15] generates the melody: the ASCII code of each characters in the string plus 96 gives the relative frequency of the corresponding note. Actually, the values are the approximate frequencies in Hz of concert pitch notes in the 3rd / small octave, i.e. with A corresponding to 220. However, since the base tone with which these values are multiplied is about 64 Hz (when played at 16 kHz, or 32 Hz when played at 8 kHz), we need to scale the result down by five octaves with >>5 to get the frequency back into a reasonable range.

Ps. If you want to try this code on a JavaScript-based bytebeat player, replace [t>>13&15] with .charCodeAt(t>>13&15).

share|improve this answer

PowerShell: 207

Golfed code:

filter n {switch($_){C{262}D{294}E{330}F{349}G{392}A{440}}}$t="CCGGAAGFFEEDDCGGFFEEDGGFFEEDCCGGAAGFFEEDDC";1..6|%{$t[0..5]|n|%{[console]::beep($_,600)};$t[6]|n|%{[console]::beep($_,1200)};$t=$t.SubString(7)}

Ungolfed, with comments:

# Filter to define note frequencies.
filter n {switch($_){C{262}D{294}E{330}F{349}G{392}A{440}}}

# Notes for Twinkle, Twinkle, Little Star.

# Run through each phrase in the song.
    # Play first six notes as quarter notes.
    # Play seventh note as half note.
    # Left-shift $t by 7 notes.

Not the greatest-sounding rendition of the song ever, but it works.

share|improve this answer
(late comment) Can you do n{ instead of n {? – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ Jun 18 at 20:35

Python 317 305 301

This is my solution, using only standard python libraries:

import math,wave,struct;d=24000;r=1100.;"t.wav","w");t.setparams((1,2,int(r),d,"NONE",""));a=[0,7,9,7];b=[5,4,2,0];c=[7,5,4,2]
for h in[math.sin(6*[240*2**(j/12.)for j in a+b+c+c+a+b][x/1000]*(x/r))*(x%500>9 or x/1000%4>2)for x in range(d)]:t.writeframes(struct.pack('h', int(h*64000/2)))

And here it is with some more whitespace for readability:

import math,wave,struct;d=24000;r=1100.
a=[0,7,9,7];b=[5,4,2,0];c=[7,5,4,2];s=[240*2**(j/12.) for j in a+b+c+c+a+b]
z=[math.sin(6*s[int(x/1000)]*(x/r))*(x%500>10 or int(x/1000)%4>2) for x in range(d)]"t.wav","w");t.setparams((1,2,int(r),d,"NONE",""))
for h in z:t.writeframes(struct.pack('h', int(h*64000./2)))
share|improve this answer

Mathematica, 86 chars

share|improve this answer

Arduino, 688

int length=15;char notes[]="ccggaag ffeeddc ggffeed ggffeed ccggaag ffeeddc";int beats[]={1,1,1,1,1,1,2,1,1,1,1,1,1,2,4};int tempo=300;void playTone(int tone,int duration){for(long i=0;i<duration*1000L;i+=tone*2){digitalWrite(11,HIGH);delayMicroseconds(tone);digitalWrite(11, LOW);delayMicroseconds(tone);}}void playNote(char note, int duration){char names[]={'c','d','e','f','g','a','b','C'};int tones[]={1915,1700,1519,1432,1275,1136,1014,956};for(int i=0;i<8;i++){if(names[i]==note){playTone(tones[i], duration);}}}void setup(){pinMode(11, OUTPUT);}void loop(){for(int i=0;i<length;i++){if(notes[i]==' '){delay(beats[i]*tempo);}else{playNote(notes[i],beats[i]*tempo);}delay(tempo/2);}}

Plug in the buzzer on output 11. I concentrated mainly on quality, but also on code length.

share|improve this answer
(late comment) "ccggaag ffeeddc ggffeed ggffeed ccggaag ffeeddc " remove space? int beats[] = remove space? for (long remove space? 11, LOW remove space? note, int remove space? i], duration remove space? 11, OUTPUT remove space? – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ Jun 18 at 11:27
Thanks, see if you can golf further. – Timtech Jun 18 at 18:29
Did you actually forget some spaces? As far as I understand, the space in ffeeddc " is for some sort of delay, which you do not need at the end, and beats[] = has no reason to have a space. Also, you should make a version concentrating on code length, just for the heck of it! – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ Jun 18 at 20:33
I suppose the variables could all be one letter but I don't think it's worth the time on such an old answer. Thanks for those tips. – Timtech Jun 18 at 21:01
Ok, feel free to post as a separate answer if you'd like. – Timtech Jun 18 at 21:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.