DEV Community

Cover image for From Text to Sound (Creating Music With The Browser)
FORCHA
FORCHA

Posted on

From Text to Sound (Creating Music With The Browser)

Case Study: Beauty And The Beast.

PlayNoise.js is a lightweight JavaScript library that enables music creation directly in the browser using Recorded Speech and YAML-based scores. It allows users to generate stereo audio and export it as WAV files, making it an excellent tool for web-based music and audio projects. Try it at PlayNoise.org.

Generate Beauty and The Beast from YAML Scores

  1. Importing the necessary Javascript libries
    <script src="https://cdn.jsdelivr.net/npm/js-yaml@4/dist/js-yaml.min.js"></script>

    <script src="pn-library.js"></script>
Enter fullscreen mode Exit fullscreen mode

The first library helps serialize the YAML data and the second library is our playnoise.

  1. Load the YAML Musical Sores to playnoise.
      const yamlContent = `
---
name: Beauty and the Beast
key: F
length: 0.4
instrument: banjo
harmonic: first
volume: 5000
sections:
  [
    {
      C1: [a4, c5, e5, 2:f5, 3:b4, a5, b5, g5, a5],
      C2: [4:a3, b3, d4, f4, b4, 2:c5, 2:e4],
    },
    { C1: [4:a4-f5, 2:a4, 0.66:c5, 0.66:e5, 0.66:f5], C2: [f3, c3, g3, 5:a3] },
    { C1: [4:b4-g5, a5, b5, g5, a5], C2: [f2, d3, f3, 3:b3, 2:e3] },
    { C1: [4:a4-f5, f4, g4, a4, b4], C2: [f3, c3, g3, 5:a3] },
    { C1: [4:e4-c5, 1.5:c5, 0.5:b4, 1.5:a4, 0.5:g4], C2: [a3, g3, f3, 5:g3] },
    {
      C1: [4:f4, 2:b4, 0.66:a4, 0.66:g4, 1.66:f4-d4, 5:c4, 2:c4-e4],
      C2: [b2b, d3, f3, b3, 4:d3-b3, 2:c3, b2b, c3, 2:f3, 2:e3],
    },
  ]

      `;
Enter fullscreen mode Exit fullscreen mode
const songData = jsyaml.load(yamlContent);
Enter fullscreen mode Exit fullscreen mode

We now convert the YAML to JSON object and save it in songdata variable.

if (typeof PN === "undefined") {
  throw new Error("PN library is not loaded");
}
Enter fullscreen mode Exit fullscreen mode

We must ensure that the PN library (a JavaScript library for creating and playing music) is available and loaded in the environment.

PN.instrument("banjo");
Enter fullscreen mode Exit fullscreen mode

The PN.instrument() function accepts a string (e.g., "banjo") to specify the instrument sound. In this case, it selects a "banjo" sound

PN.setVolume(0.5); // Set volume level
Enter fullscreen mode Exit fullscreen mode

The PN.setVolume() function takes a number between 0 (muted) and 1 (maximum volume). Here, the volume is set to 0.5, which is half the maximum.

const song = PN.createSong(songData); // Create a song from the input data
Enter fullscreen mode Exit fullscreen mode

Play with the code on codepen . you can switch to instruments like guitar, trumpet and cello.

Top comments (0)