What is the best way to combine multiple periods into a single range?

I am on a quest to find a way to transform sound frequency into light frequency, essentially turning sound into color.

Currently, I have managed to come up with a straightforward formula that converts the sound frequency into the light frequency range:

const lightFreq = frequency * Math.pow( 2, 40 );

If I want to determine the wavelength in nanometers, all I need to do is:

const waveLength = 1 / lightFreq / 10000000;

One interesting comparison between sound and color would be to associate each octave with a specific wavelength. For example, if 440Hz corresponds to a wavelength of around 640nm, then the octave at 880Hz would also be approximately 640nm.

Implementing the function could yield results like:

soundFreqToLightWaveLength( 440 ) //approx.640
soundFreqToLightWaveLength( 880 ) //approx.640
soundFreqToLightWaveLength( 1760 ) //approx.640

The wavelength falls within the range [380,780]

Answer №1

To split a frequency range into 9 segments, you'll need to take the 9th root of the factor from low to high frequencies:

let a=20,b=20000,n=9;
const fact=Math.pow(b/a,1/n);
console.log(a);
for (i=0; i<n; i++) console.log(a*=fact)

Note regarding the revised question:

The code below converts sound frequencies to light frequencies with a conversion rate of 440HZ = 640nm. Within one octave: as the sound pitch increases, the wavelength decreases:

sound frequency / Hz wavelength / nm
440 640
660 426.6666666666667
879.9999 320.0000363636406
880 640
1320 426.6666666666667
1760 640

let a=20,b=20000,n=12;

const A=440, lnA=Math.log2(A)%1;
const L=640; // base wavelength

if(1)for (let n=35,f=20,f1=20000,fact=Math.pow(f1/f,1/n);n-->-1; f*=fact) {
 let l=(lnA-Math.log2(f))%1;
 let wl=Math.pow(2,l)*L // light wavelength in nm
 console.log(f,wl)
}

This snippet covers the frequency range 20...20000Hz in 35 steps (adjustable). It maps light wavelengths for the fractional part (l=(lnA-Math.log2(f))%1) of frequencies, repetitive each octave.

Request for clarification:
Based on the latest input from OP, it seems that the wavelength calculations should follow this pattern: https://i.sstatic.net/Y63nZ.png In this scenario, the entire frequency spectrum (from lower value f0 to higher value f1) is divided into 6 sections (not octaves!), and within each section, sound frequencies are converted to wavelengths falling between wl0 (longest) and wl1 (shortest).

OP, does this align with your intentions?

If so, then this solution should suit your needs:

function calcWaveLength([f0,f1],[wl0,wl1],n){
 const lf0=Math.log(f0), lfstep=Math.log(f1/f0)/n,
       lwl0=Math.log(wl0), llrange=Math.log(wl1/wl0);
 return function(freq){ 
  lf=Math.log(freq)
  return Math.exp( lwl0 + (lf-lf0)/lfstep % 1 * llrange )
 }
}

// set up the calc function (once) for each frequency range:
const calc=calcWaveLength([20,20000],[640,460],3);

console.log("frequency,  wavelength");
[20,35.56558820077846,63.245553203367585,112.46826503806982,199.999,
 200,355.65588200778456,632.4555320336758,1124.682650380698,1999.99,
 2000,3556.558820077845,6324.555320336758,11246.82650380698,19999.9,
 20000].forEach(f=>
  console.log(f.toFixed(3),calc(f).toFixed(3))
)

The code computes according to the diagram's specifications, resembling a sawtooth wave function with sharp edges at segment ends: https://i.sstatic.net/gyHAf.png

Answer №2

// This function calculates a number between 0 and 1 based on the frequency of a pitch
// It determines the position of the pitch within an octave
// Each semitone represents 1/12th of the way from 0 to 1
// The octave starts with an A note, but you can change the number 440 for another frequency
function freqToOctavePosition(freq) {
  return ((Math.log(freq/440)/Math.log(2) % 1) + 1) % 1
}

// This function linearly converts the position within the octave to a position within a specified range
function freqToRange(freq, rangeStart, rangeEnd) {
  return (freqToOctavePosition(freq) * (rangeEnd-rangeStart)) + rangeStart
}

console.log(freqToRange(262, 400, 700))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Next.js is experiencing issues with the build process

I encountered an issue while working on a Next.js project with NextAuth.js. The problem arises when I try to define my authOptions, as a TypeScript error indicates that the object is not compatible with the expected type for AuthOptions. Here's the sn ...

Guide to displaying radio button value when updating a record

When updating a record in Node.js, I encounter an issue where the values for text input fields are rendered correctly, but the values for radio buttons and textarea in the update form do not appear. Can someone please advise on how to implement this? I am ...

The Mongoose connection keeps failing to reconnect and maintain a stable heartbeat

I am facing an issue with the automatic reconnection feature in mongoose on my project. Despite configuring it to reconnect after a certain interval, it does not work as expected. Even if the credentials are correct, mongoose should attempt to log in perio ...

steps for making a specific cell editable in tabulatorI'm happy to help

click here for image description required initializeTabulatortableBng() { let thisClass = this; let bngTableData = thisClass.tableDataWorm; function formatDecimal(cell) { var value = cell.getValue(); if (value !== null && value !== undefine ...

Exporting a named export for every HTTP method is the way to go with NextJs

I'm currently working on a project to create an Airbnb clone using NextJs. The tutorial I'm following is using an experimental version, while I've opted for the latest version of NextJs. One aspect that's been causing confusion for me i ...

What are the potential causes of an asynchronous error in a WebGLRenderingContext?

While running an animation loop, I encountered a peculiar error message that reads... GL ERROR :GL_INVALID_OPERATION : glDrawElements: Source and destination textures of the draw are the same. This error seems to occur randomly after 2 or 3 animation fr ...

When using React, the event.target method may unexpectedly return the innerText of a previously clicked element instead of the intended element that was

I have implemented a drop-down menu that triggers an event handler to return the selected option when it is clicked. Upon clicking on an option, I retrieve the inner text of that option using the event. The code snippet looks like this: event.target.inner ...

Reorganizing JSON data with ES6 techniques

I have a scenario where I need to update tire quantities in an array like this: tires: [{ name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct2", quanti ...

Initiate the execution of JavaScript functions in the loaded partial view using Ajax

I am currently working with a javaScript function that loads a partial view within my page's layout using the following logic: $('.follow-tasks').click(function (e) { e.preventDefault(); var $followtaskList = $("#td-" + $(this).attr ...

Unable to retrieve input value from dynamically-generated field with JQuery

There seems to be an issue with receiving a value from a static field when using the keyup method based on the input field class (.inputclass). Once a field is added dynamically, it does not get the value. Below is a sample code. Any help would be appreci ...

Updating cluetip content post webpage loading

I need to update the content within a cluetip after the page has finished loading. Imagine there's a button inside the cluetip and upon clicking it, I want it to disappear. Here is the cluetip setup: $('a.notice_tooltip').cluetip({activa ...

Extract information from a JSON string and present it on the screen

I am a complete novice when it comes to D3 (with very little experience in JS). Here are the lines of code I am working with: <script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16. ...

Improving the innerHTML syntax

I am looking for the correct syntax to add content to an element using innerHTML. Here is an example that isn't working as expected: openNewWindow: function(content) { popupWin = window.open(content, 'open_window', 'menubar, ...

Creating a Dropdown list using Javascript

I am currently working on implementing inline CRUD operations in MVC 5. When a user clicks a specific button to add new records, it should create a dynamic table row. Below is the JavaScript code I am using: function tblnewrow() { var newrow = ' ...

Achieving perfect alignment of an iframe on a webpage

Having an issue with aligning the iframe on my website. I have two buttons set up as onclick events that connect to internal pages displaying PHP data in tables within the iframe. Despite trying various CSS styles and positioning methods, I can't seem ...

Express and Passport encounter a Bad Request Error message

I've created a simple express API that utilizes passport.js for authentication: const express = require("express"); const app = express(); const LocalStrategy = require("passport-local").Strategy; const passport = require("passport"); passport.use( ...

Using Typescript to add an element to a specific index in an array

Currently, I am engaged in a project using Angular2 and Firebase. My goal is to consolidate all query results under a single key called this.guestPush. Within my project, there is a multiple select element with different user levels - specifically 4, 6, ...

Building a Sharepoint application with Angular 2 using the CLI and Webpack

Trying to deploy an Angular 2 CLI App to a SharePoint 2013 site has been quite challenging. The app works fine when embedded via a Content Editor Webpart, but the console throws an exception: zone.js:158 Uncaught Error: Sys.ParameterCountException: Parame ...

Change the class of <body> when the button is clicked

One of my tasks involves adding a button that, when clicked, should give the body the class "open-menu". Implementing this using jQuery was quite straightforward - I just needed to add the following line of code: $('.burger').click(function() ...

What measures can be taken to safeguard my web app from unauthorized devices attempting to connect?

I am looking for a way to restrict access to a webapp so that only authorized users can connect from approved computers or mobile devices. If a user enters the correct username and password, access will be granted only if they are using a device approved b ...