[Question]
  [
# 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.](http://www.mediafire.com/listen/gwaq93k0uh6lalk/metronome.wav))
**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 [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), 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](http://www.mediafire.com/listen/5d12f62gvzn2p92/metronome-example.wav)
  
[Answer]
## 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/#];#]&
```
[Answer]
# Pyth, ~~11~~ ~~10~~ 9 bytes
*Thanks to [Adnan](https://codegolf.stackexchange.com/questions/69927/building-a-metronome/69943?noredirect=1#comment171002_69943) for reminding me about `#`.*
```
#C7.dc60Q
```
Forever (`#`), print `C`har code `7`. Then sleep (`.d`) `60` seconds divided by (`c`) input (`Q`).
[Answer]
# 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.
[Answer]
# Bash, ~~53~~ ~~55~~ 41 bytes
Thanks to @Dennis for shaving off *14 bytes*1
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.
[Answer]
# 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](http://ethproductions.github.io/b.html). 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!
[Answer]
# [05AB1E](https://github.com/Adriandmen/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.
[Answer]
# 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
```
[Answer]
# 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]))
```
[Answer]
## [AutoIt](http://autoitscript.com/forum), 56 bytes
```
Func _($0)
While Sleep(6e4/$0)
Beep(900,99)
WEnd
EndFunc
```
[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`).
[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.
[Answer]
# 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.
[Answer]
## [GMC-4](https://en.wikipedia.org/wiki/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.
[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<<`).
[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
```
[Answer]
# 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!
[Answer]
# 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]`.
[Answer]
# Japt, 30 bytes
```
6e4/U i`?w Au¹o('../1').play()
```
The `?` should be the literal byte `9A`. [Test it online!](http://ethproductions.github.io/japt?v=master&code=NmU0L1UgaWCadyBBdblvKCcuLi8xJykucGxheSgp&input=NjA=) (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.
```
[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.
[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);}}}
```
.
[Answer]
# [ChucK](http://chuck.cs.princeton.edu/), 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.
[Answer]
# Perl 5, 36 bytes
```
{{$|=print"\a";sleep 60/$_[0];redo}}
```
A subroutine; use it as
```
sub{{$|=print"\a";sleep 60/$_[0];redo}}->(21)
```
[Answer]
# 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.
[Answer]
# [Zsh](https://www.zsh.org/), 32 bytes
```
<<<$'\a'
sleep $[60./$1]
. $0 $1
```
Based on the leading bash answer, but `source`s instead of `exec`s. The TIO link sources `$0:a` because of how the original file is executed, but it will work without it.
[Try it online!](https://tio.run/##qyrO@P/fxsZGRT0mUZ2rOCc1tUBBJdrMQE9fxTCWS09BxcAqUUHF8P///4ZGBgA "Zsh – Try It Online")
[Answer]
# Stax, 17 bytes
```
ü7»♥O╚⌂╥☻≈OyM╜Δ∩`
```
or, unpacked:
```
4|A48*x/W2|A]pc{| }*
```
The program outputs bytes that, when fed through the command line tool aplay with default setting, produce a metronome noise. The input is used as bpm
example:
```
example-stax-interpreter metronome.stax -i "60" | aplay
```
You should hear a horrible beeping noise at the desired bpm
[Answer]
# Bash + bc + [><>](https://esolangs.org/wiki/Fish), 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.
[Answer]
# SmileBASIC, 26 bytes
```
INPUT B$BGMPLAY@8T+B$+"[C]
```
It can play any general midi instrument, though anything above 9 will use more bytes.
]