Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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

Introduction

Some days ago I needed a metronome for something. I had none available so I downloaded an app from the App Store. The app had a size of 71 MB!!!
71 MB for making tic-toc...?!
So code-golf came into my mind and I was wondering if some of you guys could improve this.

Challenge

Golf some code that outputs some sound. It's pretty irrelevant what kind of sound. If required create some sound file... but a System beep will do the job as well. (Here is some sound I created... nothing special.)

Input: The beats per minute the metronome outputs.

Example

This is a non-golfed Java-version! It's just to show you the task.

public class Metronome {
  public static void main(String[] args) throws InterruptedException {
    int bpm = Integer.valueOf(args[0]);
    int interval = 60000 / bpm;

    while(true) {
        java.awt.Toolkit.getDefaultToolkit().beep();
        // or start playing the sound
        Thread.sleep(interval);
        System.out.println("Beep!");

    }
  }
}

Rules

You may not use external libaries, only tools of the language itself are allowed.
Only the bytes of the source code count... not the sound file.

This is , so the submission with the least amount of bytes wins!

EDIT:

Example output: So something like this would be the output for 120 bps: link

share|improve this question
1  
Can you add a few examples for I/O (record some sound and upload it, post the links here)? – VTCAKAVSMoACE Jan 23 at 14:25
2  
Question: when you say "external libraries", does that include the libraries that are suggested with the language? (I won't use this, but an example is in Vitsy wherein I can access shell or JS (but JS is builtin)) – VTCAKAVSMoACE Jan 23 at 17:48
3  
Can you add a leaderboard snippet in? – VTCAKAVSMoACE Jan 23 at 21:53
1  
I suspect the majority of that app you downloaded is pretty graphics and sound effects. It's like those flashlight apps that do nothing but turn the screen all white but still manage to somehow use up tens of MB... – Darrel Hoffman Jan 24 at 15:13
1  
What's the requirement on accuracy? In your sample, both beep() and console output aren't exactly instant IIRC. Neither sleep() is known for beeing accurate. – Num Lock Jan 25 at 9:04

24 Answers 24

Mathematica, 26 bytes

Pause[Beep[];60/#]~Do~∞&

Do is normally used as a "for" loop in the narrowest sense: repeat this piece of code for each i from x to y... or even just repeat this piece of code n times. Instead of a number n we can give it infinity though to create an infinite loop. The loop body is Pause[Beep[];60/#] which is just a golfy way of writing Beep[];Pause[60/#] where # is the function argument.

If it's admissible for the solution to blow up the call stack eventually, we can save one byte with a recursive solution:

#0[Beep[];Pause[60/#];#]&
share|improve this answer
    
I didn't know that ~Do~∞ was possible. A For loop only got me to 29 bytes. (Also, I personally believe that the 26-byte version is the only valid one.) – LegionMammal978 Jan 23 at 18:51
    
@LegionMammal978 Unfortunately, ~Do~∞ doesn't seem to work when the comes from a variable. (I tried using that when golfing your truth machine.) – Martin Ender Jan 23 at 18:52
1  
Attributes[Do] includes HoldAll, so my guess is that _~Do~∞ has a special evaluation pattern. – LegionMammal978 Jan 23 at 19:00
    
@LegionMammal978 It seems more like variables do, because the error message for Do[...,a] where a holds infinity actually shows the call as Do[...,{a}]. – Martin Ender Jan 23 at 19:01

Pyth, 11 10 9 bytes

Thanks to Adnan for reminding me about #.

#C7.dc60Q

Forever (#), print Char code 7. Then sleep (.d) 60 seconds divided by (c) input (Q).

share|improve this answer
    
@Adnan Forgot about that one. Thanks. – Pietu1998 Jan 23 at 18:26
    
Do you need the space? – lirtosiast Jan 23 at 18:30
    
@ThomasKwa Yes. IIRC 7. would be parsed as a number. – Cᴏɴᴏʀ O'Bʀɪᴇɴ Jan 23 at 18:30
5  
Oh. #pythnoob – Cᴏɴᴏʀ O'Bʀɪᴇɴ Jan 23 at 18:35
1  
I couldn't get .d to sleep when i tried. It kept printing unix time – busukxuan Jan 24 at 17:50

JavaScript, 36 45 42 41 34 bytes

Saved 1 byte thanks to @RikerW

Saved 1 byte thanks to @ETHproductions

n=>{for(;;sleep(60/n))print("\7")}

This is a function.

If I use `\7`, SpiderMonkey complains octal literals are deprecated.

Alternative, 31 bytes

n=>{for(;;sleep(60/n))print``}

The problem is the unprintables are stripped but this should work.

share|improve this answer
    
Dammit, I was just about to post something like this. I'm still going to post it (because it uses node and all) because I use a different approach. – VTCAKAVSMoACE Jan 23 at 18:18
    
If you look it from the way I asked the question, the recursive solution would not be possible. Metronomes are made for working and working... not for crashing after some time. – PEAR Jan 23 at 19:12
    
@PEAR this shouldn't crash because no variable is being increments. The only thing that might cause it to crash is the terminal buffer except on modern computers that could take > 50-100 years I think – Downgoat Jan 23 at 19:16
    
What environment does this run under? I've tried chrome and Node.js, but I can't get it to work. – starbeamrainbowlabs Apr 13 at 17:07
    
@starbeamrainbowlabs this uses the JavaScript shell (SpiderMonkey) – Downgoat Apr 13 at 22:02

JavaScript ES6 (browser), 43 bytes

This may be stretching the rules:

x=>setInterval('new Audio(1).play()',6e4/x)

Give this function a name (e.g. F=x=>...) and enter it in the browser console on this page. Then call the function with your bps, e.g. F(60), and wait for the magic to happen. :-)

Why does this work? Well, b.html is in the same folder as a file named 1, which is the sample sound file from the OP. I'm not sure if this is within the rules (I guess it's like the shell version; it needs to be run in a specific environment), but it was worth a shot.

Safer version, 57 bytes

If the above code isn't allowed for some reason, try this instead:

x=>setInterval('new Audio("//ow.ly/Xrnl1").play()',6e4/x)

Works on any page!

share|improve this answer
    
This is an intersting solution. It's even shorter when you download and rename the file, isn't it? – PEAR Jan 23 at 18:57
    
@PEAR That would be shorter, but then it would need its own webpage with the sound file in the same folder to run. – ETHproductions Jan 23 at 18:57
    
Oh, it's JavaScript xD... you're right – PEAR Jan 23 at 19:10
    
@PEAR There, I did it. Is this new solution within the rules? – ETHproductions Jan 23 at 19:10
    
Huh. You could specify that it is JS with the certain webpage. It's a preexisting interpreter, so it's a valid language. – VTCAKAVSMoACE Jan 23 at 19:11

Bash, 53 55 41 bytes

Thanks to @Dennis for shaving off 14 bytes1

Okay, truth time: I'm terrible at golfing bash. Any help would be so very appreciated.

echo " ";sleep `bc -l<<<60/$1`;exec $0 $1
      ^ That's ASCII char 7

1 Holy crap. No wonder nobody can outgolf Dennis.

share|improve this answer
    
Is while 1 possible? – PEAR Jan 23 at 19:02
    
@PEAR Nupe - already tried that. – VTCAKAVSMoACE Jan 23 at 19:03
    
while printf \\a perhaps? – Neil Jan 23 at 20:19
    
This doesn't work since bash uses integer division. You'll need to use bc. – quartata Jan 23 at 20:37
    
1. The BEL character isn't special to Bash, so you don't need the quotes. 2. If you read the input as a CLA, you don't need read. 3. echo exists with code 0, so you can use that statement instead of true. – Dennis Jan 24 at 2:11

Python, 68 67 57 bytes

Saved 1 byte thanks to @FlagAsSpam

Saved 9 bytes thanks to @Adnan

import time
a=input()
while 1:print"\7";time.sleep(60./a)

Also it took 2 bytes less after converting line endings to UNIX format.

Older version, that actually takes bpm as command line argument (66 bytes):

import sys,time
while 1:print"\7";time.sleep(60./int(sys.argv[1]))
share|improve this answer
4  
Can't you do print"\7";? I'm not sure, but I'm pretty sure that works. – VTCAKAVSMoACE Jan 23 at 18:16
    
@Andan No, input() requests input from user. I don't know if that's considered a valid input. Also conversion to number is needed anyway. – webwarrior Jan 23 at 21:19
1  
How about a=input() and a replacing int(sys.argv[1])? I've always thought that Python 2 automatically evaluates input and therefore doesn't need the int conversion, but I may be wrong. – Adnan Jan 24 at 11:45
    
@Andan input() actually does auto evaluate. I forgot about that feature. It's rather unpythonic though - probably a legacy from old times. – webwarrior Jan 24 at 15:15
    
Can time.sleep(60./a) be replaced with time.sleep(60./input()), while completely removing a=input()? – VoteToSpam Jan 25 at 4:47

osascript, 39 bytes

on run a
repeat
beep
delay 60/a
end
end

There is literally a command called beep? Sweeeet!

Runnable only on Mac OS X due to restricted license, but to run, do:

osascript -e "on run a
repeat
beep
delay 60/a
end
end" bpm
share|improve this answer

AutoIt, 56 bytes

Func _($0)
While Sleep(6e4/$0)
Beep(900,99)
WEnd
EndFunc
share|improve this answer

Vitsy, 14 bytes

a6*r/V1m
<wVO7

Verbose mode (interpreter coming soon):

0:                              // a6*r/V1m
push a; // 10
push 6;
multiply top two; // 60
reverse stack; // bpm on top
divide top two; // bpm/60
save/push permanent variable; 
push 1;
goto top method; // goes to 1
1:                              // <wVO7
go backward; // infinite loop, from the bottom of 1
wait top seconds;
save/push permanent variable; // pushes the bpm in terms of seconds of delay
output top as character;
push 7;

Basically, I use the w operator to wait a certain number of seconds as specified by bpm/60, wrapped in an infinite loop. Then, I make noise with the terminal output of ASCII character 7 (BEL).

share|improve this answer
    
Looks nice, but how can I test this? :) – PEAR Jan 23 at 18:58
    
@PEAR You'll have to download the interpreter (forgot to link it in the title). Save it in a file and run it with java -jar Vitsy.jar <filename>. – VTCAKAVSMoACE Jan 23 at 19:03

05AB1E, 31 bytes

Code:

I60s/[7ç?D.etime.sleep(#.pop())

If I had a built-in for waiting N seconds, this could have been 11 bytes. Unfortunately, this is not the case. Here is the explanation:

I                               # Push input
 60                             # Push 60
   s                            # Swap the top 2 items
    /                           # Divide the top 2 items
     [                          # Infinite loop
      7ç                        # Push the character \x07
        ?                       # Output it, which give a sound
         .e                     # Evaluate the following as Python code
           time.sleep(       )  # Wait for N seconds
                      #         # Short for stack
                       .pop()   # Pop the last item

Uses the ISO 8859-1 encoding.

share|improve this answer

C#, 118 bytes

class A{static int Main(string[]a){for(;;System.Threading.Thread.Sleep(60000/int.Parse(a[0])))System.Console.Beep();}}

Basic solution.

share|improve this answer
    
Why not print ASCII char 7? – VTCAKAVSMoACE Jan 23 at 19:05
    
@FlagAsSpam It's longer: The system beep uses System.Console.Beep();, and printing the character uses System.Console.Write('<\a character>');. – LegionMammal978 Jan 23 at 19:09
    
Woah. That's a lot to write a character. – VTCAKAVSMoACE Jan 23 at 19:10

Java, 103 82 bytes

Thanks to @Justin for shaving off 21 bytes!

Oh, geez.

void x(int b)throws Exception{for(;;Thread.sleep(60000/b))System.out.print('\7');}

Method and golfed version of the sample program.

share|improve this answer
    
Why not System.out.print('\7'); instead of the java.awt.Toolkit.getDefaultToolkit().beep();? – Justin Jan 24 at 1:52
    
@Justin \ is solely for escaping regex characters. – VTCAKAVSMoACE Jan 24 at 1:55
1  
no the backslash is an escape sequence. '\7' is the bell character, which makes a sound when it is printed out – Justin Jan 24 at 1:55
    
@Justin Huh. I've always thrown errors on that (when using double quotes). My mistake. Thanks! :D – VTCAKAVSMoACE Jan 24 at 11:42

GMC-4 Machine Code, 21.5 bytes

The GMC-4 is a 4-bit computer by a company called Gakken to teach the principles of assembly language in a simplified instruction set and computer. This routine takes input in data memory addresses 0x5D through 0x5F, in big-endian decimal (that is, one digit per nibble).

The algorithm is basically adding the input to memory and waiting 0.1s, until it's at least 600, and then subtracting 600 and beeping, in an infinite loop. Since the GMC-4 has a bunch of register swap functions but no register copy functions, this is done the hard way.

In hex (second line is position in memory):

A24A14A04 80EC AF5A2EF AE5A1EF AD5A0EF 8A6 F2AF09 86ADEEE9F09
012345678 9ABC DEF0123 4567890 ABCDEF0 123 456789 ABCDEF01234

In assembly:

    tiy 2     ;ld y, 0x2
    AM        ;ld a, [0x50 + y]
    tiy 1
    AM
    tiy 0
    AM
start:
    tia 0     ;ld a, 0x0
    cal timr  ;pause for (a+1)*0.1 seconds
    tiy F
    MA        ;ld [0x50 + y], a
    tiy 2
    cal DEM+  ;add a to [0x50 + y]; convert to decimal and carry.
    tiy E     ;do the same for the second digit
    MA
    tiy 1
    cal DEM+
    tiy D     ;and the third.
    MA
    tiy 0
    cal DEM+
    tia A
    M+
    jump beep
    jump start
beep:
    tia 6
    tiy D
    cal DEM-
    cal SHTS  ;'play short sound'
    jump start

Disclaimer:

I don't actually own a GMC-4. I've meticulously checked this program with documentation from online, but I may have made a mistake. I also don't know the endianness. It looks like the GMC-4 is big-endian, but I'm not sure. If anyone owns a GMC-4 and can verify this/tell me the endianness of the GMC-4, I'd much appreciate it.

share|improve this answer

C, 48 bytes

void f(int b){while(printf(""))Sleep(60000/b);}
                            ^ literal 0x07 here

A Windows-only solution (Sleep() function, to be specific).

I also (ab)used the fact that printf() returns the number of characters printed to use it as infinite loop condition.

There IS a character between double-quotes in printf() call, but it is not displayed here for some reason. If in doubt, copy and paste into Sublime Text 2 or Notepad++, the character will be displayed as BEL.

This started as a C++ solution but it kinda fell into the C-subset of C++ (because, you know, Sleep() is a bit shorter than std::this_thread::sleep_for(std::chrono::milliseconds())) and printf() is shorter than std::cout<<).

share|improve this answer

AppleScript 94 bytes

I know I'm pretty late, and this is my first post here, but whatever.

display dialog""default answer""
set x to 60000/result's text returned
repeat
beep
delay x
end

Ungolfed:

display dialog "" default answer ""
set x to 60000 / (result's text returned)
repeat
    beep
    delay x
end repeat
share|improve this answer
    
Hey, new answers :) Unfortunatly I'm unable to try your post unless I have no Mac ;) - but thanks a lot – PEAR Apr 13 at 16:32
    
@PEAR You're welcome. :) – You Apr 13 at 16:35
    
Welcome to Programming Puzzles and Code Golf. This is good answer, +1. Please keep answering! – wizzwizz4 Apr 13 at 17:09

VBScript, 113 66 bytes

a=InputBox("")
Do
WScript.Echo(Chr(7))
WScript.Sleep(60000/a)
Loop

This program is simple enough; it takes input, echoes the BEL character, and waits. Thanks to Niel for shaving off almost half the program!

share|improve this answer
    
What's wrong with WScript.Echo CHR(7)? Also, did you mean 60000? – Neil Jan 23 at 20:18
    
@Neil Ah, yes. forgot about those.; – Cᴏɴᴏʀ O'Bʀɪᴇɴ Jan 23 at 21:00

Ruby, 37 33 bytes

m=->b{loop{puts"\7"
sleep 6e1/b}}

Pretty straightforward.

This is a lambda function. If you wanted 60 bpm, you'd do: m[60].

share|improve this answer
    
Theoretically $><<?\a should also work for the beep. And no need to give a name for your proc (all JavaScript solutions with fat arrow function also leave it unassigned), you can call it anonymously too: ->b{loop{$><<?\a;sleep 6e1/b}}[60]. – manatwork Jan 24 at 14:32
    
@manatwork I only have Ruby 2.x, so I couldn't test the ?\a; do you have Ruby 1.x? If so, can you test that this works? – Justin Jan 24 at 17:24
    
Well, I have a Ruby 1.9.3 and the code raises no error with it. But I have another problem with the testing: no beep on my machine. Neither Ruby nor anything else. Set something once, no idea what. – manatwork Jan 24 at 17:35

Japt, 30 bytes

6e4/U i`?w Au¹o('../1').play()

The ? should be the literal byte 9A. Test it online! (Sorry about the pop-up delaying the first few beats; this will be removed soon.)

How it works

6e4/U i"new Audio('../1').play()  // Implicit: U = input bps
6e4/U                             // Calculate 60000 / U.
      i                           // Set a timed event every that many milliseconds,
       "new Audio('../1').play()  // running this code every time.
                                  // ../1 is the path to the file used in my JS entry.
share|improve this answer

Mumps, 18 bytes

R I F  H 60/I W *7

Read the BPM into variable I, then F {with two spaces after} is an infinate loop. Halt for 60 seconds / BPM, then write $CHR(7) {Ascii: BEL} to standard output, giving the audio output required, then restart at the infinite loop.

share|improve this answer

Java, 321 chars

Sounds very good. Works only on systems with MIDI support.

import javax.sound.midi.*;import java.util.*;class A{public static void main(String[] a) throws Exception{int d=new Scanner(System.in).nextInt();Synthesizer b=MidiSystem.getSynthesizer();b.open();MidiChannel c=b.getChannels()[0];c.programChange(116);while(true){c.noteOn(0,100);Thread.sleep((int)(d/.06));c.noteOff(0);}}}

.

share|improve this answer
    
Looks nice, but this does not work for me: pastebin.com/0CbGYkU0 – PEAR Jan 30 at 21:21
    
@PEAR fixed. I forgot a cast. – username.ak Jan 31 at 12:24
    
@PEAR and an import – username.ak Jan 31 at 12:33
    
@PEAR, i had swapped some ops because of no sound – username.ak Jan 31 at 19:02

ChucK, 90 bytes

White noise that is turned on and off every two ticks.

60./Std.atoi(me.arg(0))*1000=>float s;while(1){Noise b=>dac;s::ms=>now;b=<dac;s::ms=>now;}

Explanation

60./Std.atoi(me.arg(0)) //Convert the input to an int and divide 60 by it
*1000                   //Multiply by 1000 (in order to avoid s::second)
=>float s;              //Store it as a float in variable s
while(1)                //Forever,
{Noise b=>dac;          //Connect a noise generator b to the audio output
s::ms=>now;             //Wait for s milliseconds
b=<dac;                 //Disconnect b from the audio output
s::ms=>now;}            //Wait for s milliseconds

This is made to turn on the sound on a beat, then turn it off on the beat after.

98 93 byte version (fancier)

White noise played for 10 milliseconds per tick.

60./Std.atoi(me.arg(0))*1000-9=>float s;while(1){Noise b=>dac;10::ms=>now;b=<dac;s::ms=>now;}

This is made to be a click instead of constant noise being turned on and off.

share|improve this answer

Perl 5, 36 bytes

{{$|=print"\a";sleep 60/$_[0];redo}}

A subroutine; use it as

sub{{$|=print"\a";sleep 60/$_[0];redo}}->(21)
share|improve this answer
    
sleep is in seconds, so you can't have more than 60 beeps per minute, not sure if that's a requirement. Also, you can probably keep the same byte count but have a full program by doing something like: $|=<>;{print"\a";sleep 60/$|;redo} (can't test it right now). – ChatterOne Jan 25 at 20:18
    
@ChatterOne, according to its documentation, you're right about sleep. But it worked for me. – msh210 Jan 28 at 15:47

Jolf, 7 bytes, noncompeting

I added sounds after this very fine challenge was made.

TΑa/Αaj
T       set an interval
 Αa      that plays a short beep (Α is Alpha)
   /Αaj  every 60000 / j (the input) seconds. (Αa returns 60000)

If you so desire to clear this sound, take note of the output. Say that number is x. Execute another Jolf command ~CP"x", and the interval will be cleared.

share|improve this answer

Bash + bc + ><>, 44 bytes

Playing on the fact that the ><> interpreter lets you define a tick time :

python fish.py -t $(bc -l<<<"2/$1/60") -c 7o

The ><> code is 7o and should output the BEL character, producing a system beep. It will loop until interrupted.
The -t value is set to (2 / RPM ) / 60 so that the whole code is played RPM * 60 times per second.

share|improve this answer
    
Thanks a lot for a new answer after some amount of time after publishing. Doesn't work for me :( Not sure if a problem of my system or something else. I downloaded the fish.py from GitHub and executed your commad (openSUSE). Got this error: (standard_in) 1: syntax error usage: fish.py [-h] (<script file> | -c <code>) [<options>] fish.py: error: argument -t/--tick: expected one argument – PEAR Apr 13 at 16:40
    
Have you got bc installed? It looks like the $(bc -l<<<"2/$1/60") did not produce any output. I'll add it to the list of languages of the answer. I haven't been able to fully test my answer yet, so there might be some kind of error too. – Aaron Apr 13 at 16:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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