DEV Community

Discussion on: Make the sound of Mario's coins in your browser!

Collapse
 
kurokky profile image
kurokky(黒木シンタロー)

Thank you. Changed.

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

No problem!

The halving/doubling to go down/up an octave is pretty fun. You could do something like this, mapping an octave to its relevant power of 2:

const coin = (octave) => {
    const multiplier = 2 ** octave

    const audioContext = new (window.AudioContext ?? window.webkitAudioContext)()

    const gainNode = audioContext.createGain()

    gainNode.connect(audioContext.destination)
    gainNode.gain.value = 0.1

    const oscillator = audioContext.createOscillator()

    oscillator.connect(gainNode)
    oscillator.type = "square"

    oscillator.frequency.setValueAtTime(987.766 * multiplier, audioContext.currentTime)
    oscillator.frequency.setValueAtTime(1318.51 * multiplier, audioContext.currentTime + 0.08)

    oscillator.start()
    oscillator.stop(.5)
}

;(async () => {
    for (let i = -7; i < 4; ++i) {
        coin(i)

        await new Promise(res => setTimeout(res, 1000))
    }
})()
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
kurokky profile image
kurokky(黒木シンタロー)

I thought of that method too, but since the pitch of the average rate shifts slightly, I use a correspondence table. (Added to the article.)

Thread Thread
 
lionelrowe profile image
lionel-rowe

Nice!