Building a Mini Composing Device with Tone.js: Learning Scales and Tempo Through Clicks

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About This Article
This article is generated through an automated workflow utilizing generative AI. Using fictitious data and browser operations, we will learn the use cases, mechanics, and failure observation points of Tone.js. No access to real services or personal information is performed.

Verification Status:Verified against official documentation and GitHub fixed commit HTML/JavaScript on 2026-10-30. Real browser operations, CDN acquisition, and rendering/audio output were not executed, and the results in the text are expected values from the code.

ItemContent
TargetModern browsers such as Chrome, Edge, and Firefox (actual device compatibility unverified)
Library UsedTone.js (Version in tutorial: 15.1.22)
CostNo paid API is required for the demo source itself. Communication fees and usage terms depend on the environment
DataFictitious data within the page. No credentials, location information, or corporate data required
Learning OperationPlay a 4-note melody and change the tempo

Why Test This Technology?

With JavaScript, you can not only change screen colors and positions, but also create sound. Tone.js is a library designed to make the Web Audio API easier to handle. In this tutorial, we will sound four notes: C, E, G, and high C. Rather than playing recorded instrument audio files, the key feature is generating synthesizer sounds within the browser and playing them back at timed intervals. Because results can be heard even if the visual screen does not change, it is an intuitive topic for understanding event-driven and time-based programming. To prevent sudden loud volumes, the demo starts muted, and precautions regarding volume settings are emphasized.

When creating a working sample, rather than stopping at the mere fact that the visual interface moved, you need to distinguish which input modified which variable and which process updated the rendering. In this learning material, those changes are explicitly displayed on the screen. When integrating into an actual service, please design authentication and persistence processes separately.

Try First: Live Demo and Expected Results

Set the browser speaker volume to low and click "Play 4 Notes". If successful, four notes should be heard, and the status is expected to change to Reserved. Next, lower the BPM from 100 to 60 and check whether the interval between notes becomes longer. BPM stands for Beats Per Minute, representing the number of beats in one minute. Raising it to 180 shortens the interval. If no sound is produced, isolate browser permissions, device mute status, and audio output destinations in other tabs. In audio experiments, do not assume visual SUCCESS displays alone constitute auditory execution success.

Things to Check Before Operation

  1. Confirm that your PC can execute JavaScript. Administrator privileges are not required.

  2. Open the browser developer tools and prepare to check the Console for errors and the Network tab for CDN fetch failures.

  3. If the demo is not actually published, save the Daily Codeindex.htmlandapp.jsin the same folder and open them using a local HTTP server. When using modules, direct execution via file:// is not guaranteed to work.

  4. Compare the results before and after the operation. If they differ from the expected values, record what failed to display first.

Overview of the Mechanism

flowchart LR
    A["入力やクリック"] --> B["イベントを受ける"]
    B --> C["Tone.js のAPI"]
    C --> D["状態と描画を更新"]
    D --> E["見た目と文字で確認"]

This diagram is a conceptual illustration for learning purposes and does not represent internal browser implementations or detailed network communications. Regardless of the library, tracing how operations reach specific variables remains consistent.

Local Verification When the Public Demo Is Unavailable

The fixed commitHTML fileandJavaScript filefrom GitHub's Raw view, respectivelyindex.htmlandapp.jsSave them in the same new folder. The README alone will not make it work. On Windows, open PowerShell in that folder,py -3 -m http.server 8000 --bind 127.0.0.1and on Linux/macOS, runpython3 -m http.server 8000 --bind 127.0.0.1, then openhttp://127.0.0.1:8000/on the same PC. To exit, pressCtrl+Cin the terminal. Because the browser fetches the library core from an external CDN, check the Console and Network errors if a connection cannot be established. This procedure serves as a reproduction guide and is not a browser measurement report for this article.

How it works: Decoding the API

Browsers restrict audio playback before any user interaction has occurred. Tone.start() must be called in response to a user action such as a click. The sound source is created using Tone.Synth and connected to the speaker output path via toDestination. triggerAttackRelease specifies the pitch, duration, and start time. Scheduling playback using AudioContext timestamps makes it easier to design timing than playing notes one by one using JavaScript setTimeout.

Reading the minimal code

await Tone.start(); // クリックのイベント内で呼ぶ
const synth = new Tone.Synth({volume: -18}).toDestination();
synth.triggerAttackRelease("C4", "8n", Tone.now());

The above is an excerpt highlighting the key points of the API. It is not a complete, standalone file ready for copy-pasting and execution.The complete HTML and implementation set required to run it can be found in the README/demo files on the Daily Code side. Trace which functions select HTML elements and which lines update numeric values, then test with known placeholder values.

Comparing by changing only one condition

Changing the note sequence from C4, E4, G4, C5 to C4, F4, G4, B4 alters the resonance. While frequencies can be written as numerical values, using note names is easier to read initially. Changing the note duration may cause notes to overlap with adjacent ones. Therefore, the time interval between playback schedules and the duration of a single note must be considered separately. When expanding to continuous playback, the handling of scheduled notes during stop, resume, and tempo change operations becomes critical.

The comparison procedure involves recording the initial value, changing only one location, and checking whether the result appears in the expected area. Changing multiple inputs at once makes it impossible to determine what caused an effect. Verify the process all the way back to reverting to the pre-change state.

Where to look when failures occur

Pressing the play button repeatedly causes audio to overlap. Rather than continuously creating new instruments each time, the sample essentially reuses the sound source. When stopping, resources are disposed of for cleanup, but the relationship with scheduled notes requires additional verification in an actual browser. When publishing at an event venue, it is important not to autoplay audio, to ensure that a mute operation is always accessible, and to provide supplementary visual information with consideration for hearing.

Observed statePoints to isolateExample response
The screen remains in its initial stateScript acquisition, initialization, and event registrationCheck Console, Network, and script tags
The display changes, but the values are incorrectInput values, arrays, units, and update targetsFix values and verify condition by condition
The button is unclickableSelectors and DOM generation orderCheck the HTML to ensure IDs match
Works only on certain devicesBrowser features, permissions, CDNs, and performanceRecord the device type, version, and steps to reproduce

Errors occurring within the browser are distinct from outages on a public web server. The former should be investigated via error details in the developer tools, while the latter should be analyzed through HTTP responses and asset delivery conditions. Refraining from describing unknown failures as successes enhances the credibility of technical notes.

Application to Business and Learning

This can be applied to feedback in typing learning materials, game sound effects, timing practice, and pitch visualization. However, playing notification sounds depends on the device state, and critical warnings should not rely on sound alone. Business systems require a design that combines on-screen text, notification history, and audio.

Determinations Before Implementation

When publishing to readers, determine the source of the displayed data, who can modify it, the types of information retained on the screen, and the verification items when updating libraries. This demo includes neither login nor server persistence. Therefore, before adding operational features, we recommend first distinguishing between the minimum functional part that displays as expected and the parts requiring operational reliability, permissions, and backups. Since third-party CDNs involve external communication, prior verification is required to ensure they are permitted within corporate networks.

Comparison with Alternative Methods

MethodSuitable ScenariosPoints to note
Tone.jsScenarios matching your goals, such as playing a four-note melody and changing the tempoRequires updating dependency libraries and managing usage terms
Browser standard APIBuilding small features yourselfChecking specifications and compatibility on your own
Static images and tablesExplanations requiring no interactionCannot experience state changes in real time

Libraries are tools to be chosen when needed. Compare what you want to achieve against the learning cost. Avoiding making the inclusion of a library an end in itself makes smaller pages easier to maintain.

GitHub Sample

The blog post focuses on background and philosophy, while Daily Code provides executable and modifiable code, separating their roles. APIs for posting and saving to external services are not included.

Official Information / Primary Sources

Reviewed Reference Scope:Refer to the official documentation as of the October 27, 2026 edit. This does not guarantee future changes to linked destinations or all CDN asset responses.

Supplementary Information on Validation Scope

The fixed sources stored in GitHub were cross-checked with the official API descriptions. Browser operations, CDN loading, and results on various operating systems have not been verified. When confirming actual operation, check the Console and Network tabs, and do not conclude that all conditions were successful based solely on a SUCCESS display on the screen.

Document information

Article title
Building a Mini Composing Device with Tone.js: Learning Scales and Tempo Through Clicks
Published
Updated
Source
https://papanda925.com/?p=18289&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL