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: https://soundcloud.com/raveloris/a-440-hz
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>
21 Answers 21
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.
-
\$\begingroup\$ This program does not satisfy the last requirement: "The output must be in the form of a sine wave".
SOUNDcommand 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 theSOUNDcommand should produce a square wave. \$\endgroup\$pabouk - Ukraine stay strong– pabouk - Ukraine stay strong2015年11月16日 09:56:23 +00:00Commented 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– lynn2015年11月16日 11:33:10 +00:00Commented Nov 16, 2015 at 11:33
Python2, 40 bytes
from winsound import*
Beep(input(),5000)
Only works on Windows.
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.
-
2\$\begingroup\$ You can save one character by using
2^-12instead of1/4096. \$\endgroup\$flawr– flawr2015年11月17日 10:49:04 +00:00Commented Nov 17, 2015 at 10:49 -
\$\begingroup\$ Oh silly me,
8^-4is even shorter! \$\endgroup\$flawr– flawr2015年11月18日 16:28:26 +00:00Commented Nov 18, 2015 at 16:28
PowerShell, 32 bytes
[console]::beep((read-host),5kb)
C#, 80 bytes
class P{static void Main(string[]a){System.Console.Beep(int.Parse(a[0]),5000);}}
-
\$\begingroup\$ Do you know what is the alternative for
Beeping in Java? \$\endgroup\$user41805– user418052015年11月18日 20:23:59 +00:00Commented Nov 18, 2015 at 20:23
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.
-
\$\begingroup\$ Where's the STDIN? \$\endgroup\$cat– cat2015年12月19日 13:16:39 +00:00Commented Dec 19, 2015 at 13:16
-
1\$\begingroup\$
RDAreads a number from STDIN and puts it in registerA. \$\endgroup\$lynn– lynn2015年12月19日 15:43:04 +00:00Commented 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– cat2015年12月19日 15:43:50 +00:00Commented Dec 19, 2015 at 15:43
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.)
-
\$\begingroup\$ Is there a \x07 in there? \$\endgroup\$TheDoctor– TheDoctor2015年11月15日 23:19:53 +00:00Commented Nov 15, 2015 at 23:19
-
\$\begingroup\$ No, xset does all the beeping stuff. \$\endgroup\$a spaghetto– a spaghetto2015年11月15日 23:20:16 +00:00Commented 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\$a spaghetto– a spaghetto2015年11月15日 23:45:38 +00:00Commented Nov 15, 2015 at 23:45
-
\$\begingroup\$
echo <BEL>where<BEL>is the actual character, saves 6 bytes. \$\endgroup\$Dennis– Dennis2015年11月16日 16:35:52 +00:00Commented Nov 16, 2015 at 16:35 -
\$\begingroup\$ @Dennis D'oh. Thanks! \$\endgroup\$a spaghetto– a spaghetto2015年11月16日 17:14:23 +00:00Commented Nov 16, 2015 at 17:14
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
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].
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
-
\$\begingroup\$ This won't play for 5 seconds because
prompt()is called after the audio timer is started atnew AudioContext(). I believe the shortest you can get this is 115 bytes withc=new AudioContext(p=prompt());with(c.createOscillator()){frequency.value=p;connect(c.destination);start();stop(5)}. \$\endgroup\$user81655– user816552015年11月16日 03:45:14 +00:00Commented Nov 16, 2015 at 3:45 -
\$\begingroup\$ Thanks for the heads up, I appreciate the idea of using 'with' as well. \$\endgroup\$Taylor G– Taylor G2015年11月16日 04:00:56 +00:00Commented 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 thepassignment, and just settingfrequency.value=prompt()should get you down to 110. \$\endgroup\$Mwr247– Mwr2472015年11月16日 21:11:01 +00:00Commented 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– Taylor G2015年11月16日 23:13:42 +00:00Commented 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\$Patrick Roberts– Patrick Roberts2017年02月07日 15:09:46 +00:00Commented Feb 7, 2017 at 15:09
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
-
1\$\begingroup\$ That could be reduced getting the command line argument in main args instead
Main(a()As StringandBeep(a(0),5000)reducing the total to 74 bytes according to byte counter \$\endgroup\$Sehnsucht– Sehnsucht2015年11月19日 19:01:09 +00:00Commented Nov 19, 2015 at 19:01
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.
-
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– vsz2015年11月17日 06:03:58 +00:00Commented 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– SztupY2015年11月17日 09:51:35 +00:00Commented Nov 17, 2015 at 9:51
-
\$\begingroup\$ The requirements say "Input must be taken in through STDIN", so skip that lengthy
ParamStr()and justRead()it as required: pastebin.com/1Tw2d0D6 \$\endgroup\$manatwork– manatwork2016年01月24日 19:46:09 +00:00Commented Jan 24, 2016 at 19:46
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
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.
-
\$\begingroup\$ Cool answer. Nice work. \$\endgroup\$Riker– Riker2016年01月24日 17:51:03 +00:00Commented Jan 24, 2016 at 17:51
-
\$\begingroup\$ You used Vitsy. <3 My child is redeemed. \$\endgroup\$Addison Crump– Addison Crump2016年01月24日 17:59:47 +00:00Commented Jan 24, 2016 at 17:59
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.
-
\$\begingroup\$ Don't you need to pass
&xtoscanf? Also you can declarexas a parameter to main and let the compiler default its type. \$\endgroup\$Neil– Neil2015年11月18日 00:59:17 +00:00Commented Nov 18, 2015 at 0:59 -
\$\begingroup\$ @Neil, I don't know how I mistyped it without passing
&xtoscanf(). Fixed now; thanks. \$\endgroup\$user46778– user467782015年11月18日 14:55:08 +00:00Commented Nov 18, 2015 at 14:55
Hassium, 38 Bytes
func main()Console.beep(input(), 5000)
C (gcc), 59 bytes
i,j;f(x){for(i=4e4;i--;)putchar(j=128+128*sin(i*x/1274.));}
Outputs samples to standard output suitable for an 8 bit 8 kHz DAC such as ./aplay available on many Linux distributions.
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.
-
\$\begingroup\$ Input should be taken via STDIN, not hardcoded. \$\endgroup\$flawr– flawr2015年11月17日 10:47:13 +00:00Commented Nov 17, 2015 at 10:47
-
\$\begingroup\$ @flawr I don`t know any methods of precise input on Shadertoy. Please enlighten me. \$\endgroup\$Kroltan– Kroltan2015年11月17日 11:58:42 +00:00Commented 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– flawr2015年11月17日 12:11:55 +00:00Commented 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– Kroltan2015年11月17日 12:14:31 +00:00Commented Nov 17, 2015 at 12:14
-
\$\begingroup\$ Can you load files? That's what I did. \$\endgroup\$geokavel– geokavel2015年11月17日 19:01:23 +00:00Commented Nov 17, 2015 at 19:01
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.
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.
beep()function. Is it guaranteed that that is a sine wave? \$\endgroup\$System.Console.Beepthing is a sine wave on my (modern, Windows 10) machine, so I think that counts. Solutions on PPCG generally needn't be portable. \$\endgroup\$