24
\$\begingroup\$

This is a rather simple challenge, but I couldn't find any question that was really similar to it. The challenge is to take a frequency in using STDIN or an equivalent, and then output a tone that matches that frequency, in Hz, for 5 seconds. For example

Input: 400
Output: (a tone of 400 Hz with a duration of 5 seconds)

Rules

  • Input must be taken in through STDIN, or your language's equivalent
  • The answer must be a full program
  • Builtins may be used
  • The frequency will be anywhere from 50 - 5000 Hz
  • The output must be played for 5 seconds
  • The output must be in the form of a sine wave

Test cases

Input: 440

Output:

Input: 200

Output:

Input: 4000

Output:


  • This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

  • Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

    Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

    Also note that languages do have to fullfil our usual criteria for programming languages.


Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 63967; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 39060; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

\$\endgroup\$
6
  • \$\begingroup\$ Would a function be acceptable? \$\endgroup\$ Nov 15, 2015 at 21:51
  • \$\begingroup\$ @quartata It should be a full program. \$\endgroup\$ Nov 15, 2015 at 21:51
  • 2
    \$\begingroup\$ I see that a lot of people are using a beep() function. Is it guaranteed that that is a sine wave? \$\endgroup\$
    – geokavel
    Nov 16, 2015 at 5:19
  • 2
    \$\begingroup\$ Windows' System.Console.Beep thing is a sine wave on my (modern, Windows 10) machine, so I think that counts. Solutions on PPCG generally needn't be portable. \$\endgroup\$
    – Lynn
    Nov 16, 2015 at 11:32
  • \$\begingroup\$ Is printing out an audio file a valid way to "output a tone"? \$\endgroup\$ Nov 17, 2015 at 3:10

20 Answers 20

12
\$\begingroup\$

QBasic, 18 bytes (disqualified)

Like @pabouk mentioned, this uses the PC speaker, so it plays a square wave, not a sine wave like the problem asks. (This requirement was added to the problem after this answer was posted, hence the votes.) I'll leave it here for posterity anyway.


INPUT F
SOUND F,91

Play a sound at the inputted frequency for 91 ticks, which is equal to 5 seconds.

\$\endgroup\$
2
  • \$\begingroup\$ This program does not satisfy the last requirement: "The output must be in the form of a sine wave". SOUND command uses the PC speaker which as designed was driven by a timer chip 8254 which produces a square wave. --- Though in modern PCs 8254 could be missing correct emulation of the SOUND command should produce a square wave. \$\endgroup\$ Nov 16, 2015 at 9:56
  • 3
    \$\begingroup\$ This requirement was added after I posted my answer. :/ I'll add a note, but I feel weird about deleting this answer when it's the one voted to the top. \$\endgroup\$
    – Lynn
    Nov 16, 2015 at 11:33
11
\$\begingroup\$

Python2, 40 bytes

from winsound import*
Beep(input(),5000)

Only works on Windows.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Would 5e3 work? \$\endgroup\$
    – Lynn
    Nov 15, 2015 at 22:00
  • 3
    \$\begingroup\$ @Mauris No, I had already tried that but it wants integers only. \$\endgroup\$
    – orlp
    Nov 15, 2015 at 22:01
9
\$\begingroup\$

Mathematica, 42 bytes

Well if we can use built-ins...

Input[]
EmitSound@Play[Sin[2t%Pi],{t,0,5}]

Thanks to the requirement for a full program, this was the first time I got to use my recently discovered golfing tip of using % (result of last evaluation) to save two bytes.

Mathematica also has a built-in Sound which takes a pitch and a duration as arguments, but unfortunately the pitch has to be given as a musical note. Specifying your own sound wave via Play seems to be the only way to work with a frequency.

\$\endgroup\$
7
\$\begingroup\$

MATLAB, 36 bytes

sound(sin(pi*input('')*(0:8^-4:10)))

Thanks to flawr for saving two bytes.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ You can save one character by using 2^-12 instead of 1/4096. \$\endgroup\$
    – flawr
    Nov 17, 2015 at 10:49
  • \$\begingroup\$ Oh silly me, 8^-4 is even shorter! \$\endgroup\$
    – flawr
    Nov 18, 2015 at 16:28
6
\$\begingroup\$

C#, 80 bytes

class P{static void Main(string[]a){System.Console.Beep(int.Parse(a[0]),5000);}}
\$\endgroup\$
1
  • \$\begingroup\$ Do you know what is the alternative for Beeping in Java? \$\endgroup\$
    – user41805
    Nov 18, 2015 at 20:23
6
\$\begingroup\$

PowerShell, 32 bytes

[console]::beep((read-host),5kb)
\$\endgroup\$
2
  • 4
    \$\begingroup\$ Is the space really needed? \$\endgroup\$
    – kasperd
    Nov 16, 2015 at 7:33
  • \$\begingroup\$ wow, sloppy of me \$\endgroup\$
    – Nacht
    Nov 16, 2015 at 21:28
4
\$\begingroup\$

FakeASM, 12 bytes

RDA
BEEP 5e3

Works with the Windows reference implementation (download). It calls Windows' Beep function, which is a sine wave on modern platforms.

\$\endgroup\$
3
  • \$\begingroup\$ Where's the STDIN? \$\endgroup\$
    – cat
    Dec 19, 2015 at 13:16
  • 1
    \$\begingroup\$ RDA reads a number from STDIN and puts it in register A. \$\endgroup\$
    – Lynn
    Dec 19, 2015 at 15:43
  • \$\begingroup\$ I ended up reading the spec and noticing that but I forgot to delete my comment. thanks, though \$\endgroup\$
    – cat
    Dec 19, 2015 at 15:43
4
\$\begingroup\$

Bash + X11, 27 20 bytes

xset b 9 $1 5;echo 

This contains an unprintable, so here's a hexdump:

0000000: 7873 6574 2062 2039 2024 3120 353b 6563  xset b 9 $1 5;ec
0000010: 686f 2007                                ho .

This takes the frequency as a command-line argument and plays the appropriate beep at a volume of 9% (since no volume was specified).

(Note: I was unable to test this due to some issues with my computer, but I'm 99% sure it works.)

\$\endgroup\$
6
  • \$\begingroup\$ Is there a \x07 in there? \$\endgroup\$
    – TheDoctor
    Nov 15, 2015 at 23:19
  • \$\begingroup\$ No, xset does all the beeping stuff. \$\endgroup\$ Nov 15, 2015 at 23:20
  • \$\begingroup\$ @TheDoctor Oh I see what you mean... it does need a \x07 to make the actual noise. Fixing. \$\endgroup\$ Nov 15, 2015 at 23:45
  • \$\begingroup\$ echo <BEL> where <BEL> is the actual character, saves 6 bytes. \$\endgroup\$
    – Dennis
    Nov 16, 2015 at 16:35
  • \$\begingroup\$ @Dennis D'oh. Thanks! \$\endgroup\$ Nov 16, 2015 at 17:14
4
\$\begingroup\$

Bash + Linux utils, 95

bc -l<<<"obase=16;for(;t<5;t+=1/8000){a=s($1*t*6.3);scale=0;a*30/1+99;scale=9}"|xxd -p -r|aplay

This is a true sine wave. No beeps. Input frequency entered via the command-line:

./hz.sh 440
\$\endgroup\$
3
\$\begingroup\$

Processing, 148 114 106 bytes

import processing.sound.*;
Engine.start().sinePlay(int(loadStrings("s")[0]),1,0,0,0);delay(5000);exit();

(For some reason Processing requires both using the import statement and the new line, otherwise it does not recognize the library.)

I still haven't figured out how to pass arguments into Processing, though I know it's possible, so this code requires having a file called "s" in the sketch folder which has the frequency value. If I can figure out how to pass in arguments I could replace file loading with args[0].

\$\endgroup\$
3
\$\begingroup\$

JavaScript, 114 bytes

p=prompt();c=new AudioContext;with(c.createOscillator()){frequency.value=p;connect(c.destination);start();stop(5)}

Requires a somewhat cutting-edge browser, enter the frequency in the prompt. JSFiddle

\$\endgroup\$
5
  • \$\begingroup\$ This won't play for 5 seconds because prompt() is called after the audio timer is started at new AudioContext(). I believe the shortest you can get this is 115 bytes with c=new AudioContext(p=prompt());with(c.createOscillator()){frequency.value=p;connect(c.destination);start();stop(5)}. \$\endgroup\$
    – user81655
    Nov 16, 2015 at 3:45
  • \$\begingroup\$ Thanks for the heads up, I appreciate the idea of using 'with' as well. \$\endgroup\$
    – Taylor G
    Nov 16, 2015 at 4:00
  • \$\begingroup\$ I've not seen <script> tags as being required for JavaScript to considered a full program before. I think you're good for the 114. Also, removing the p assignment, and just setting frequency.value=prompt() should get you down to 110. \$\endgroup\$
    – Mwr247
    Nov 16, 2015 at 21:11
  • \$\begingroup\$ @Mwr247 Unfortunately, as user81655 pointed out, the timer which determines when the audio stops starts when the AudioContext is created. The prompt has to appear before then, or a slow input could result shorter audio or no audio at all. \$\endgroup\$
    – Taylor G
    Nov 16, 2015 at 23:13
  • \$\begingroup\$ p=prompt();with(new AudioContext)with(createOscillator())frequency.value=p,connect(destination),start(),stop(5) this saves 3 bytes \$\endgroup\$ Feb 7, 2017 at 15:09
3
\$\begingroup\$

VB.net, 90 bytes, 74 bytes

Module m
Sub Main(a() as String)
Console.Beep(a(0),5000)
End Sub
End Module

Thanks to Sehnsucht

Module m
Sub Main()
Console.Beep(My.Application.CommandLineArgs.First,5000)
End Sub
End Module

This is my first post so if I did any thing wrong please let me know

\$\endgroup\$
1
  • 1
    \$\begingroup\$ That could be reduced getting the command line argument in main args instead Main(a()As String and Beep(a(0),5000) reducing the total to 74 bytes according to byte counter \$\endgroup\$
    – Sehnsucht
    Nov 19, 2015 at 19:01
2
\$\begingroup\$

Turbo/Borland/Free/GNU Pascal, 95 bytes

Due to issues with the delay function on modern computers (well, anything faster than 200Mhz) trying to run Turbo / Borland pascal, this might not wait 5 seconds, even with a patched CRT library

Program a;Uses crt;Var i,k:Integer;BEGIN Val(ParamStr(1),i,k);Sound(i);Delay(5000);NoSound;END.

The String to Integer conversion can be done shorter (77 bytes) on FreePascal, and modern derivates, as they have the StrToInt function:

Program a;Uses crt;BEGIN Sound(StrToInt(ParamStr(1)));Delay(5000);NoSound;END.
\$\endgroup\$
3
  • 1
    \$\begingroup\$ As far as I know, a Pascal program will work fine with all compilers even without the Program a; part, so you can win 10 bytes with omitting it. \$\endgroup\$
    – vsz
    Nov 17, 2015 at 6:03
  • \$\begingroup\$ @vsz FPC might be fine (so I can remove that from the second snippet), I still have to check some ancient ones, like TP5.5, as far as I remember they required it. \$\endgroup\$
    – SztupY
    Nov 17, 2015 at 9:51
  • \$\begingroup\$ The requirements say “Input must be taken in through STDIN”, so skip that lengthy ParamStr() and just Read() it as required: pastebin.com/1Tw2d0D6 \$\endgroup\$
    – manatwork
    Jan 24, 2016 at 19:46
2
\$\begingroup\$

Perl, 27 bytes

Basically a Perl version of the Python answer (also only works on Windows), if we're allowing modules.

use Audio::Beep;beep<>,5000
\$\endgroup\$
2
\$\begingroup\$

Vitsy + X11, 20 bytes

"5 "WX" 9 b tesx",7O

A translation of my bash answer. Does not work in the online interpreter (obviously).

Takes input as any non-numeric character followed by the frequency (so for an input of 440 Hz you could do "a440").

Explanation

"5 "WX" 9 b tesx",7O
"5 "                   Push " 5"
    WX                 Reads input and removes the first character (which is used to force string context)
      " 9 b tesx"      Push "xset b 9 "
                 ,     Pop everything and execute as a shell command.
                  7O   Output bell char.
\$\endgroup\$
2
  • \$\begingroup\$ Cool answer. Nice work. \$\endgroup\$
    – Riker
    Jan 24, 2016 at 17:51
  • \$\begingroup\$ You used Vitsy. <3 My child is redeemed. \$\endgroup\$ Jan 24, 2016 at 17:59
1
\$\begingroup\$

C with WinAPI, 82 bytes

#include<windows.h>
#include<stdio.h>
main(){int x;scanf("%i",&x);Beep(x,5000);}

Uses the WinAPI Beep() function.

\$\endgroup\$
2
  • \$\begingroup\$ Don't you need to pass &x to scanf? Also you can declare x as a parameter to main and let the compiler default its type. \$\endgroup\$
    – Neil
    Nov 18, 2015 at 0:59
  • \$\begingroup\$ @Neil, I don't know how I mistyped it without passing &x to scanf(). Fixed now; thanks. \$\endgroup\$
    – user46778
    Nov 18, 2015 at 14:55
1
\$\begingroup\$

Hassium, 38 Bytes

func main()Console.beep(input(), 5000)
\$\endgroup\$
0
\$\begingroup\$

Shadertoy GLSL Sound Shader, 86

#define F 440.0
vec2 mainSound(float t){return vec2(sin(6.3*F*t)*(t<5.0?1.0:0.0));}

"Input" is given via #define. Outputs a sinewave with approximate frequency of FHz. Rounded 2*Pi to 6.3, instead of "default" 6.2831, but sounds pretty much the same.

Sadly there isn't much to golf here.

\$\endgroup\$
6
  • \$\begingroup\$ Input should be taken via STDIN, not hardcoded. \$\endgroup\$
    – flawr
    Nov 17, 2015 at 10:47
  • \$\begingroup\$ @flawr I don`t know any methods of precise input on Shadertoy. Please enlighten me. \$\endgroup\$
    – Kroltan
    Nov 17, 2015 at 11:58
  • \$\begingroup\$ This is should be your task, not mine. But I do not know Shadertoy anyway so I cannot help you. \$\endgroup\$
    – flawr
    Nov 17, 2015 at 12:11
  • \$\begingroup\$ @flawr the only method of reasonable precision would be the cursor position, but that is only available to image shaders, not sound shaders. So I'm pretty much stuck with defines. \$\endgroup\$
    – Kroltan
    Nov 17, 2015 at 12:14
  • \$\begingroup\$ Can you load files? That's what I did. \$\endgroup\$
    – geokavel
    Nov 17, 2015 at 19:01
0
\$\begingroup\$

Jolf, 4 bytes, noncompeting

This language addition came after the challenge.

Αc5j
Αc     create a beep
  5     five seconds long
   j    with the input as a frequency

The default wave is a sine wave.

\$\endgroup\$
0
\$\begingroup\$

SmileBASIC, 84 bytes

INPUT F
N=LOG(F/440,POW(2,1/12))+57BGMPLAY FORMAT$("@D%D@255T12N%D",(N-(N<<0))*63,N)

Converts from Hz to half steps, and plays the a certain note with the a detune value to produce the frequency.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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