Ask coding questions

← Back to all posts
Javascript Songs
WilliamXing (49)

This is how to play happy birthday in javascript:

((c=new AudioContext(),n=[...'畋畋畍甯畋甯畐甯畏甯甯甯畋畋畍甯畋甯畒甯畐甯甯甯畋畋畗甯畔甯畐畐畏甯畍甯甯甯畕畕畔甯畐甯畒甯畐甯甸甼甿町甽甿町甽甿甸甼甿甸甿畂甸甽畁畄町甿畃甼甿畄'].map(a=>a.charCodeAt(0)-30000),z=c.currentTime,t=(f,b,o=c.createOscillator(),g=c.createGain(),l=0.5)=>(o.frequency.value=f,o.connect(g),g.connect(c.destination),g.gain.setValueAtTime(0.5,z+b),g.gain.linearRampToValueAtTime(0,z+b+l),o.start(z+b),o.stop(z+b+l)))=>n.forEach((c,i)=>~c&&t(220*2**((c)/12),(i>=47?(i-47)*2:i+(i%2)/6)/4)))()

How can I play other songs?

Answered by ANDREWVOSS (78) [earned 5 cycles]
View Answer
Comments
hotnewtop
ANDREWVOSS (78)

Usually you should play songs from an audio file, for example download a song as audio.mp3 and then do:

var audio = new Audio("audio.mp3");
audio.play();
WilliamXing (49)

I don't want to do it like that @ANDREWVOSS

ANDREWVOSS (78)

@WilliamXing That's the best way to do it, but I'm sure you can find other ways

notGilbert (109)

The happy birthday song is encoded as a unicode? string, just replace the string in [...'string'] with your own,

(use codes that are in the 0x75__ series)
https://unicodelookup.com/ might be helpful

=====

here's mary had a little lamb (G is out of tune ik):

((c=new AudioContext(),n=[...'畍畋畆畋田畍畍畍田畋畋畋田畍畍畍田畍畋畆畋田畍畍畍畋畋畍畋畆'].map(a=>a.charCodeAt(0)-30000),z=c.currentTime,t=(f,b,o=c.createOscillator(),g=c.createGain(),l=0.5)=>(o.frequency.value=f,o.connect(g),g.connect(c.destination),g.gain.setValueAtTime(0.5,z+b),g.gain.linearRampToValueAtTime(0,z+b+l),o.start(z+b),o.stop(z+b+l)))=>n.forEach((c,i)=>~c&&t(220*2**((c)/12),(i>=47?(i-47)*2:i+(i%2)/6)/4)))()
notGilbert (109)

@notGilbert I used as a rest because it's decimal equaivalent is 30000, the code does x - 30000 to determine the frequency to play, so 30000 - 30000 = 0, no sound

notGilbert (109)

@WilliamXing so you know that sounds are made out of tiny vibrations in air. The Audio.createOscillator() creates an oscillator, which can play those frequency. So it takes those characters in that string, turns them into numbers and them plays them using the audio interface.

The reason why you see chinese characters is because chinese characters are convenient located in the 30,000 unicode range. For example, the first character is “ 畋” which is 30,027 (decimal). It then subtracts 30000 from it then plays the frequency.

loop over all the letters and then you get a sonh