www.xbdev.net
xbdev - software development
Sunday March 30, 2025
Home | Contact | Support | Fractals Natures pattern... | Fractals in Sound, Audio and Music Natures patterns...
     
 

Fractals in Sound, Audio and Music

Natures patterns...

 


Fractals are more than pretty patterns - they
Fractals are more than pretty patterns - they're a fundamental characteristic in signals and waveforms - such as 'sound' form voice patterns to music.


Fractals > Sound, Audio and Music Fractals


Fractal algorithms offer a unique approach to generating music and sounds that captivates both creators and listeners due to their inherent beauty, flexibility, and simplicity. Traditionally associated with creating visually stunning graphical effects that mimic the complexity and intricacy of natural phenomena, fractals also possess the remarkable ability to produce organic and natural sounds, expanding their creative potential into the realm of auditory artistry.

One of the most striking features of fractal music and sound generation is their inherent beauty. Fractals exhibit self-similarity across different scales, resulting in structures that are aesthetically pleasing and harmonious to the human senses. This self-similarity manifests in musical compositions as recurring motifs, patterns, or rhythms that resonate with listeners on both a conscious and subconscious level. By harnessing the mathematical elegance of fractal algorithms, composers can craft compositions that evoke a sense of awe and wonder, inviting listeners on a journey through intricately woven sonic landscapes.

The flexibility of fractal algorithms allows for endless exploration and experimentation in music and sound design. Fractals offer a versatile framework for creating a wide range of musical elements, including melodies, harmonies, rhythms, textures, and timbres. Composers can manipulate fractal parameters to control the complexity, structure, and dynamics of their compositions, tailoring the sonic output to suit their artistic vision. Whether seeking to evoke the serene tranquility of natural environments or the chaotic beauty of abstract landscapes, fractal algorithms provide a rich palette of sonic possibilities for musical expression.

The simplicity of fractal music and sound generation belies the complexity and depth of the resulting compositions. Despite their mathematical underpinnings, fractal algorithms offer an intuitive and accessible means of creating music and sounds, making them accessible to artists and enthusiasts across diverse backgrounds and skill levels. By embracing the elegance of simplicity, fractal-based compositions invite listeners to engage with the music on a visceral level, transcending intellectual abstraction to connect with the primal essence of sound.

Fractals are beautiful yet flexible and capable of generating a diverse range of music and sounds that offer compelling avenues for artistic exploration and expression. From the mesmerizing intricacy of self-similar structures to the boundless creative potential of algorithmic composition, fractals enrich the sonic landscape with their organic and natural qualities. By harnessing the power of fractal algorithms, composers and sound designers can unlock new realms of auditory beauty, inviting listeners to immerse themselves in the enchanting world of fractal music and sound.

Creating a sound using fractals can be quite interesting.

• Fractal Sound using Mandelbrot Set
• Brownian Noise Fractal
• Perlin Fractal Noise
• Fractal Music
• Cantor Rhythm Fractal

For example the following presents simplified minimal working examples (completely self contained) that run in a web-page (using JavaScript).

Fractal Sound using Mandelbrot Set (JavaScript)


One way to create sound with fractaisl is by generating a waveform using a fractal algorithm such as the Mandelbrot set and then converting it into an audio signal.

The example below works by generating a waveform by iterating through points in the Mandelbrot set and converts it into an audio signal. You can adjust parameters such as the duration, sample rate, and frequency to modify the sound. Keep in mind that this is a basic example, and you can explore more complex fractal algorithms and audio synthesis techniques for more interesting sounds.


<script>
// Constants
const SAMPLE_RATE 44100;
const 
DURATION 3// Duration of the sound in seconds

// Function to generate Mandelbrot set values
function mandelbrot(c_realc_imagmax_iter) {
    
let z_real 0;
    
let z_imag 0;
    
    for (
let i 0max_iteri++) {
        const 
temp_real z_real z_real z_imag z_imag c_real;
        const 
temp_imag z_real z_imag c_imag;
        
        
z_real temp_real;
        
z_imag temp_imag;
        
        if (
z_real z_real z_imag z_imag 4) {
            return 
max_iter;
        }
    }
    
    return 
1;
}

// Function to generate audio buffer
function generateSound() {
    const 
bufferSize Math.floor(DURATION SAMPLE_RATE);
    const 
buffer = new Float32Array(bufferSize);

    for (
let i 0bufferSizei++) {
        const 
SAMPLE_RATE;
        const 
frequency 440// You can change this to adjust the pitch
        
const c_real Math.cos(frequency Math.PI 2);
        const 
c_imag Math.sin(frequency Math.PI 2);
        const 
value mandelbrot(c_realc_imag100); // Adjust max_iter for different complexity
        
buffer[i] = value 1// Scale to the range [-1, 1]
    
}

    return 
buffer;
}

// Function to play audio
function playSound(buffer) {
    const 
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    const 
audioBuffer audioCtx.createBuffer(1buffer.lengthSAMPLE_RATE);
    
audioBuffer.getChannelData(0).set(buffer);

    const 
source audioCtx.createBufferSource();
    
source.buffer audioBuffer;
    
source.connect(audioCtx.destination);
    
source.start();
}

let b document.createElement('button');
b.innerHTML 'Play Fractal Sound';
document.body.appendChild);
b.onclick = ()=>{
    
// Generate and play the sound
    
const soundBuffer generateSound();
    
playSound(soundBuffer);
}
</
script>


Brownian Noise Fractal (Fractal Noise)


The example below generates three seconds of Brownian noise, also known as fractal noise, which has a sound reminiscent of static or wind. You can adjust the intensity of the noise by changing the multiplier in the generateBrownianNoise function. The duration of the sound can be modified by changing the DURATION constant, and the sample rate by changing the SAMPLE_RATE.

<script>
// Constants
const SAMPLE_RATE 44100;
const 
DURATION 3// Duration of the sound in seconds

// Function to generate Brownian noise
function generateBrownianNoise(length) {
    const 
buffer = new Float32Array(length);
    
let value 0.0;
    
    for (
let i 0lengthi++) {
        
buffer[i] = value;
        
value += (Math.random() * 1) * 0.5// Adjust the multiplier for different intensity
        
value Math.min(Math.max(value, -1), 1); // Clamp the value to [-1, 1]
    
}
    
    return 
buffer;
}

// Function to generate audio buffer
function generateSound() {
    const 
bufferSize Math.floor(DURATION SAMPLE_RATE);
    return 
generateBrownianNoise(bufferSize);
}

// Function to play audio
function playSound(buffer) {
    const 
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    const 
audioBuffer audioCtx.createBuffer(1buffer.lengthSAMPLE_RATE);
    
audioBuffer.getChannelData(0).set(buffer);

    const 
source audioCtx.createBufferSource();
    
source.buffer audioBuffer;
    
source.connect(audioCtx.destination);
    
source.start();
}

let b document.createElement('button');
b.innerHTML 'Play Fractal Sound';
document.body.appendChild);
b.onclick = ()=>{
    
// Generate and play the sound
    
const soundBuffer generateSound();
    
playSound(soundBuffer);
}
</
script>


Perlin Fractal Noise


The below code uses Perlin noise to generate a smooth noise waveform. The generatePerlinNoise function creates Perlin noise by combining multiple octaves of noise at different frequencies and amplitudes. The noise function is based on Perlin's improved noise algorithm, which interpolates smoothly between pseudo-random gradients.

<script>
// Constants
const SAMPLE_RATE 44100;
const 
DURATION 3// Duration of the sound in seconds

// Function to generate Perlin noise
function generatePerlinNoise(length) {
    const 
buffer = new Float32Array(length);
    
let value 10.0;
    
let frequency 60.0;
    
let amplitude 10.0;

    for (
let i 0lengthi++) {
        
buffer[i] = value;
        
frequency *= 2// Increase frequency for each octave
        
amplitude *= 0.5// Decrease amplitude for each octave
        
value += noise(SAMPLE_RATE frequency) * amplitude;
    }

    return 
buffer;
}

// Function to generate Perlin noise
function noise(x) {
    const 
Math.floor(x) & 255;
    
-= Math.floor(x);
    const 
fade(x);
    return 
lerp(ugrad(p[X], x), grad(p[1], 1)) * 2;
}

function 
fade(t) {
    return 
* (* (15) + 10);
}

function 
lerp(tab) {
    return 
* (a);
}

function 
grad(hashx) {
    return (
hash 1) === : -x;
}

const 
= new Uint8Array(512);

for (
let i 0256i++) {
    
p[i] = p[256] = Math.floor(Math.random() * 256);
}

// Function to generate audio buffer
function generateSound() {
    const 
bufferSize Math.floor(DURATION SAMPLE_RATE);
    return 
generatePerlinNoise(bufferSize);
}

// Function to play audio
function playSound(buffer) {
    const 
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    const 
scriptNode audioCtx.createScriptProcessor(409611); // bufferSize, input channels, output channels
    
scriptNode.onaudioprocess = function(audioProcessingEvent) {
        const 
outputBuffer audioProcessingEvent.outputBuffer.getChannelData(0);
        for (
let i 0outputBuffer.lengthi++) {
            
outputBuffer[i] = buffer[buffer.length];
        }
    };

    
scriptNode.connect(audioCtx.destination);
}

let b document.createElement('button');
b.innerHTML 'Play Fractal Sound';
document.body.appendChild);
b.onclick = ()=>{
    
// Generate and play the sound
    
const soundBuffer generateSound();
    
playSound(soundBuffer);
}
</
script>




Fractal Music


Generating fractal music involves creating musical patterns or structures that exhibit self-similarity or other fractal properties. One approach is to use fractal algorithms to generate melodies, rhythms, or other musical elements.

We define a simple melody pattern represented a series of numbers. The generateFractalMusic function recursively generates variations of the melody pattern at different depths. The playPattern function plays the melody pattern using a simple playTone function. When the "Generate Fractal Music" button is clicked, the generateFractalMusic function is called to generate and play the fractal music.

<html lang="en">
<
head>
<
meta charset="UTF-8">
<
meta name="viewport" content="width=device-width, initial-scale=1.0">
<
title>Fractal Music Generation</title>
<
script src="https://cdnjs.cloudflare.com/ajax/libs/midi.js/0.3.0/midi.min.js"></script>
</
head>
<
body>
<
button onclick="generateFractalMusic()">Generate Fractal Music</button>
</
body>
<
script>

// Create audio context
const AudioContext window.AudioContext || window.webkitAudioContext;
const 
audioContext = new AudioContext();

// Function to generate a tone
function playTone(frequencyduration) {
  const 
oscillator audioContext.createOscillator();
  
oscillator.type 'sine'// You can change the type of wave here (sine, square, sawtooth, triangle)
  
oscillator.frequency.setValueAtTime(frequencyaudioContext.currentTime);
  
oscillator.connect(audioContext.destination);
  
oscillator.start();
  
setTimeout(() => {
    
oscillator.stop();
  }, 
duration);
}

// Example usage
//playTone(440, 1000); // Play a 440 Hz tone for 1 second


// Define a simple melody pattern
const melodyPattern = [60626465676971];

// Function to generate fractal music
function generateFractalMusic(depth 3pattern melodyPattern) {
    if (
depth === 0) {
        
// Play the pattern at this level
        
playPattern(pattern);
    } else {
        
// Generate variations of the pattern and recurse
        
generateFractalMusic(depth 1pattern);
        
generateFractalMusic(depth 1pattern.map(note => note 2));
        
generateFractalMusic(depth 1pattern.map(note => note 2));
        
generateFractalMusic(depth 1pattern.reverse());
    }
}

// Function to play a pattern
function playPattern(pattern) {
    const 
delay 500// Delay between notes in milliseconds
    
pattern.forEach((noteindex) => {
        
setTimeout(() => {
            
playTonenote500 ); // play tone 0.5 second
        
}, index delay);
    });
}
</
script>
</
html>


Things to Try

You can customize and experiment with different melody patterns, recursion depths, and musical elements to create more complex fractal music. Additionally, you can explore other playback functions (e.g., mix in other audio effects or save the sound and mix/download it for use later on).




Cantor Rhythm Fractal


Generating a music rhythm using a fractal technique called the Cantor set. The Cantor set is a fractal subset of the real number line with some interesting self-similar properties. We'll use its structure to generate a simple rhythm pattern and output this as audio music.

<html lang="en">
<
head>
<
meta charset="UTF-8">
<
meta name="viewport" content="width=device-width, initial-scale=1.0">
<
title>Cantor Set Rhythm Generation</title>
</
head>
<
body>
<
button onclick="generateCantorRhythmAndPlay()">Generate Cantor Set Rhythm</button>
</
body>
<
script>
// Create audio context
const AudioContext window.AudioContext || window.webkitAudioContext;
const 
audioContext = new AudioContext();

// Function to generate a tone
function playTone(frequencyduration) {
  const 
oscillator audioContext.createOscillator();
  
oscillator.type 'sine'// You can change the type of wave here (sine, square, sawtooth, triangle)
  
oscillator.frequency.setValueAtTime(frequencyaudioContext.currentTime);
  
oscillator.connect(audioContext.destination);
  
oscillator.start();
  
setTimeout(() => {
    
oscillator.stop();
  }, 
duration);
}

// Example usage
//playTone(440, 1000); // Play a 440 Hz tone for 1 second

async function delay(time) {
  return new 
Promise(resolve => setTimeout(resolvetime));
}

// Function to generate Cantor set rhythm
function generateCantorRhythm(depth 3length 16) {
    
console.log('generateCantorRhythm');
    if (
depth === 0) {
        
// End recursion
        
return ['1'];
    } else {
        
// Generate variations of the rhythm pattern
        
const prevRhythm generateCantorRhythm(depth 1length 3);
        const 
cantorRhythm prevRhythm.concat(prevRhythm.map(sub => sub '0'.repeat(length 3)) , prevRhythm);
        return 
cantorRhythm;
    }
}

// Function to play rhythm
async function playRhythm(rhythm) {
    
console.log('playRythm');
    const 
notes rhythm.split('');
    for (
let n=0n<notes.lengthn++)
    {
        
let note notes[n];
        if (
note === '1'
        {
            
//console.log( note );
            
playTone440500 );
        }
        else
        {
            
//console.log( note );
            //playTone( 140, 1000 );
        
}
        
await delay(500);
    };
}

// Function to generate and play Cantor set rhythm
function generateCantorRhythmAndPlay() {
    
console.log('generateCantorRhythmAndPlay');
    const 
depth 3// Depth of Cantor set recursion
    
const length 16// Total length of rhythm pattern
    
const cantorRhythm generateCantorRhythm(depthlength);

    
console.logcantorRhythm );

    
playRhythm(cantorRhythm.join(''));
}
</
script>
</
html>









 
Advert (Support Website)

 
 Visitor:
Copyright (c) 2002-2025 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.