Home > OS >  Inserting timeOut into code but it is not creating the pause
Inserting timeOut into code but it is not creating the pause

Time:12-17

//In order to run in terminal insert the following code to activate localhost: npx parcel src/index.html
import { chordType, transpose , note } from '@tonaljs/tonal';
import { chord } from '@tonaljs/chord';
import { entries } from '@tonaljs/chord-dictionary';
import { Howler, howl } from 'howler';

const sound = new Howl({
    src: ['assets/pianosprite.mp3'],
    onl oad() {
        console.log('Sound file has been loaded. Do something here!');
        soundEngine.init();
    },
    onl oaderror(e, msg) {
        console.log('Error', e, msg);
    }
});

const startNotes = ['C', 'C#', 'Db', 'D', 'D#', 'Eb', 'E', 'F', 'F#', 'Gb', 'G', 'G#', 'Ab', 'A', 'A#', 'Bb', 'B']; 

const startNoteSelector = document.querySelector('#start-note');
const octaveSelector = document.querySelector('#octave');
const buttons = document.querySelector('.buttons');
const intervalsInChord = document.querySelector('.intervals-in-chord');
const notesInChord = document.querySelector('.notes-in-chord');

let selectedStartNote = 'C';
let selectedOctave = '1';
let selectedChord;

const app = {
    init() {
        this.setupStartNotes();
        this.setupOctaves();
        this.setupButtons();
        this.setupEventListeners();
    },
    setupStartNotes() {
        startNotes.forEach(noteName => {
            let noteNameOption = this.createElement('option', noteName);
            startNoteSelector.appendChild(noteNameOption);
        });
    },
    setupOctaves() {
        for (let i = 1; i <= 4; i  ) {
            let octaveNumber = this.createElement('option', i);
            octaveSelector.appendChild(octaveNumber);
        }
    },
    setupButtons() {
        const chordNames = entries().map(entry => {
            return entry.aliases[0];
        }); 
        chordNames.forEach(chordName => {
            let chordButton = this.createElement('button', chordName);
            buttons.appendChild(chordButton);
        });
        
    },
    setupEventListeners() {
        startNoteSelector.addEventListener('change', () => {
            selectedStartNote = startNoteSelector.value;
        });
        octaveSelector.addEventListener('change', () => {
            selectedOctave = octaveSelector.value;
        });
        buttons.addEventListener('click', (event) => {
            if (event.target.classList.contains('buttons')) {
                return;
            }
            selectedChord = event.target.innerText;
            this.displayAndPlayChord(selectedChord);
        });
    },
    displayAndPlayChord(selectedChord) {
        let chordIntervals = chord(selectedChord).intervals;
        intervalsInChord.innerText = chordIntervals.join(' - ');
        
        const startNoteWithOctave = selectedStartNote   selectedOctave;
        let chordNotes = chordIntervals.map(val => {
            return transpose(startNoteWithOctave, val);
        });
        notesInChord.innerText = chordNotes.join(' - ');
        soundEngine.play(chordNotes);
    },
    createElement(elementName, content) {
        let element = document.createElement(elementName);
        element.innerHTML = content;
        return element;
    }
}

const soundEngine = {
    init() {
        const lengthOfNote = 2400;
        let timeIndex = 0;
        for (let i = 24; i <= 96; i  ) {
            sound['_sprite'][i] = [timeIndex, lengthOfNote];
            timeIndex  = lengthOfNote;
        }
        
    },

    play(soundSequence) {
        const buttons =
        document.querySelector(".buttons");

        const chordNameTable = {
        "5": " perfect fifth",
        "M7#5sus4": "major seven augmented fifth suspended fourth",
        "7#5sus4": "dominant seven augmented fifth suspended fourth",
        "sus4": "suspended fourth",
        "M7sus4": "major seven suspended fourth",
        "7sus4": "dominant seven suspended fourth",
        "7no5": "dominant seven no fifth",
        "aug": "Augmented",
        "M7b6": "major seven minor sixth",
        "maj7#5": "major seven augmented fifth",
        "7#5": "dominant seven augmented fifth"
          }

          buttons.addEventListener("click", (event) => {
            const sayThis = chordNameTable[event.target.textContent];
            textToSpeech(sayThis, event.target.textContent);
          })
          function textToSpeech(message, chord) {
            const speech = new SpeechSynthesisUtterance();
            speech.lang = "en-US";
            speech.text = message;
            speech.volume = 1;
            speech.rate = 1;
            speech.pitch = 1;
            window.speechSynthesis.speak(speech);
            // When speaking has finished
            speech.onend = function() {
              playChord(chord);
            }
          }
          
          function playChord(chord) {
            // Wait a second (1000 miliseconds) before playing the chord
            setTimeout(() => {
              // Play the chord here
              console.log("Chord to be played", chord);
            }, 100000);
          }

        const chordMidiNumbers = soundSequence.map(noteName => {
            return note(noteName).midi;
        });
        sound.volume(0.05);
        chordMidiNumbers.forEach(noteMidiNumber => {
            
            sound.play(noteMidiNumber.toString());
        });
    }

}

app.init();

app.init();

const allChordNames = entries()
chordEntries.map(entry => {
    return entry.aliases[0];
})
console.log(Array.isArray (allChordNames));//In order to run in terminal insert the following code to activate localhost: npx parcel src/index.html
import { chordType, transpose , note } from '@tonaljs/tonal';
import { chord } from '@tonaljs/chord';
import { entries } from '@tonaljs/chord-dictionary';
import { Howler, howl } from 'howler';

const sound = new Howl({
    src: ['assets/pianosprite.mp3'],
    onl oad() {
        console.log('Sound file has been loaded. Do something here!');
        soundEngine.init();
    },
    onl oaderror(e, msg) {
        console.log('Error', e, msg);
    }
});

const startNotes = ['C', 'C#', 'Db', 'D', 'D#', 'Eb', 'E', 'F', 'F#', 'Gb', 'G', 'G#', 'Ab', 'A', 'A#', 'Bb', 'B']; 

const startNoteSelector = document.querySelector('#start-note');
const octaveSelector = document.querySelector('#octave');
const buttons = document.querySelector('.buttons');
const intervalsInChord = document.querySelector('.intervals-in-chord');
const notesInChord = document.querySelector('.notes-in-chord');

let selectedStartNote = 'C';
let selectedOctave = '1';
let selectedChord;

const app = {
    init() {
        this.setupStartNotes();
        this.setupOctaves();
        this.setupButtons();
        this.setupEventListeners();
    },
    setupStartNotes() {
        startNotes.forEach(noteName => {
            let noteNameOption = this.createElement('option', noteName);
            startNoteSelector.appendChild(noteNameOption);
        });
    },
    setupOctaves() {
        for (let i = 1; i <= 4; i  ) {
            let octaveNumber = this.createElement('option', i);
            octaveSelector.appendChild(octaveNumber);
        }
    },
    setupButtons() {
        const chordNames = entries().map(entry => {
            return entry.aliases[0];
        }); 
        chordNames.forEach(chordName => {
            let chordButton = this.createElement('button', chordName);
            buttons.appendChild(chordButton);
        });
        
    },
    setupEventListeners() {
        startNoteSelector.addEventListener('change', () => {
            selectedStartNote = startNoteSelector.value;
        });
        octaveSelector.addEventListener('change', () => {
            selectedOctave = octaveSelector.value;
        });
        buttons.addEventListener('click', (event) => {
            if (event.target.classList.contains('buttons')) {
                return;
            }
            selectedChord = event.target.innerText;
            this.displayAndPlayChord(selectedChord);
        });
    },
    displayAndPlayChord(selectedChord) {
        let chordIntervals = chord(selectedChord).intervals;
        intervalsInChord.innerText = chordIntervals.join(' - ');
        
        const startNoteWithOctave = selectedStartNote   selectedOctave;
        let chordNotes = chordIntervals.map(val => {
            return transpose(startNoteWithOctave, val);
        });
        notesInChord.innerText = chordNotes.join(' - ');
        soundEngine.play(chordNotes);
    },
    createElement(elementName, content) {
        let element = document.createElement(elementName);
        element.innerHTML = content;
        return element;
    }
}

const soundEngine = {
    init() {
        const lengthOfNote = 2400;
        let timeIndex = 0;
        for (let i = 24; i <= 96; i  ) {
            sound['_sprite'][i] = [timeIndex, lengthOfNote];
            timeIndex  = lengthOfNote;
        }
        
    },

    play(soundSequence) {
        const buttons =
        document.querySelector(".buttons");

        const chordNameTable = {
        "5": " perfect fifth",
        "M7#5sus4": "major seven augmented fifth suspended fourth",
        "7#5sus4": "dominant seven augmented fifth suspended fourth",
        "sus4": "suspended fourth",
        "M7sus4": "major seven suspended fourth",
        "7sus4": "dominant seven suspended fourth",
        "7no5": "dominant seven no fifth",
        "aug": "Augmented",
        "M7b6": "major seven minor sixth",
        "maj7#5": "major seven augmented fifth",
        "7#5": "dominant seven augmented fifth"
          }

          buttons.addEventListener("click", (event) => {
            const sayThis = chordNameTable[event.target.textContent];
            textToSpeech(sayThis, event.target.textContent);
          })
          function textToSpeech(message, chord) {
            const speech = new SpeechSynthesisUtterance();
            speech.lang = "en-US";
            speech.text = message;
            speech.volume = 1;
            speech.rate = 1;
            speech.pitch = 1;
            window.speechSynthesis.speak(speech);
            // When speaking has finished
            speech.onend = function() {
              playChord(chord);
            }
          }
          
          function playChord(chord) {
            // Wait a second (1000 miliseconds) before playing the chord
            setTimeout(() => {
              // Play the chord here
              console.log("Chord to be played", chord);
            }, 100000);
          }

        const chordMidiNumbers = soundSequence.map(noteName => {
            return note(noteName).midi;
        });
        sound.volume(0.05);
        chordMidiNumbers.forEach(noteMidiNumber => {
            
            sound.play(noteMidiNumber.toString());
        });
    }

}

app.init();

app.init();

const allChordNames = entries()
chordEntries.map(entry => {
    return entry.aliases[0];
})
console.log(Array.isArray (allChordNames));
body {
    font-family: Lato, Sans-serif;
    color: #fff;
    background: #000000
}

.controls{
    display: flex;
    justify-content: center;
}
.controls select {
    margin: 0 10px;
}
.chord-notes {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 1.5em;
}
.chord-notes p {
    margin: 10px 0;
}
/*width makes the page more condensed towards the left*/
.buttons {
    display: flex;
    flex-wrap: wrap;
    width: 60%;
}
/*min-width divides columns into 3 instead of 4, max-width creates a set size for the button*/
.buttons button{
    flex-grow: 1;
    min-width: 20%;
    max-width: 20%;
    height: 50px;
    font-size: 1em;
    background: #7200CC;
    border: none;
    color: #fff;
    margin: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chord Dictionary</title>
    <link rel="stylesheet" href="styles.css">
    <head>
      
        <style>
        ul {
          list-style-type: none;
          margin: 0;
          padding: 0;
          overflow: hidden;
          background-color: #333;
        }
        
        li {
          float: left;
        }
        
        li a {
          display: block;
          color: white;
          text-align: center;
          padding: 14px 16px;
          text-decoration: none;
        }
        
        li a:hover {
          background-color: #A400DD;
        }
        </style>
        </head>
       </head>
            <ul>
          <li><a  href="#home">Home</a></li>
          <li><a href="#lessons">Lessons</a></li>
          <li><a href="#practice">Practice</a></li>
          <li><a href="#test">Test</a></li>
          <li><a href="#sign up">Sign Up</a></li>
          <li><a href="#login">Login</a></li>
        </ul>
</head>

<body>
    <div >
        <label for="start-note">Start note:</label>
        <select name="start note" id="start-note">
           
        </select>
        <label for="octave">Octave: </label>
        <select name="Octave" id="octave">
            
        </select>
    </div>
    <div >
        <p >C3 - D3 - E3 - F#3 - A3</p>
        <p >P1 - M3 - P5 - M7</p>
    </div>
    <div >
        
    </div>
    <script type="module" src="mock.index.js"></script>
</body>
</html>

I have initially created a chord library that plays many different chords at the click of a button, and even implemented a function in which the code will also say the name of the chord. Now the issue I have run into has been that in order for the chord library to work setTimeout has been implemented which is not working at the moment. Ideally I would like for the chord library to first say the name of the chord and then play the chord. Unfortunately instead of the chord library running those actions, the chord library will say the name of the chord and play the chord at the same time with the voice that says the name of the chord repeating the name of the chord multiple times. Where exactly am I doing things wrong with this code?

const soundEngine = {
    init() {
        const lengthOfNote = 2400;
        let timeIndex = 0;
        for (let i = 24; i <= 96; i  ) {
            sound['_sprite'][i] = [timeIndex, lengthOfNote];
            timeIndex  = lengthOfNote;
        }
        
    },

    play(soundSequence) {
        const buttons =
        document.querySelector(".buttons");

        const chordNameTable = {
        "5": " perfect fifth",
        "M7#5sus4": "major seven augmented fifth suspended fourth",
        "7#5sus4": "dominant seven augmented fifth suspended fourth",
        "sus4": "suspended fourth",
        "M7sus4": "major seven suspended fourth",
        "7sus4": "dominant seven suspended fourth",
        "7no5": "dominant seven no fifth",
        "aug": "Augmented",
        "M7b6": "major seven minor sixth",
        "maj7#5": "major seven augmented fifth",
        "7#5": "dominant seven augmented fifth"
          }

          buttons.addEventListener("click", (event) => {
            const sayThis = chordNameTable[event.target.textContent];
            textToSpeech(sayThis, event.target.textContent);
          })
          function textToSpeech(message, chord) {
            const speech = new SpeechSynthesisUtterance();
            speech.lang = "en-US";
            speech.text = message;
            speech.volume = 1;
            speech.rate = 1;
            speech.pitch = 1;
            window.speechSynthesis.speak(speech);
            // When speaking has finished
            speech.onend = function() {
              playChord(chord);
            }
          }
          
          function playChord(chord) {
            // Wait a second (1000 miliseconds) before playing the chord
            setTimeout(() => {
              // Play the chord here
              console.log("Chord to be played", chord);
            }, 100000);
          }

CodePudding user response:

Thanks for updating the question, now the problem is clear.

In setupEventListeners you are saying that anytime a user clicks on something inside <div >, you want to run displayAndPlayChord:

buttons.addEventListener('click', (event) => {
  if (event.target.classList.contains('buttons')) {
    return;
  }
  selectedChord = event.target.innerText;
  this.displayAndPlayChord(selectedChord);
});

In displayAndPlayChord, you are doing some work and then running soundEngine.play

The play method is doing a few things:

  1. Creating a local copy of the functions textToSpeech and playChord
  2. Looking for <div > and saying that when they are clicked they run textToSpeech
  3. And, immediately playing the chords in soundSequence (because it's after the other function declarations. The functions are only created, not run at this point)

When textToSpeech is run, it says the name of the chord, and then once it's finished runs playChord.

playChord at the moment waits one second and then does nothing.

The issue here is that you now have two click handlers on .buttons, so when you click a button, displayAndPlayChord and textToSpeech both run, which is why they're happening at the same time.

Worse, now you have three click handlers on button!!

So to fix, you want to remove the addEventListener from play, so it doesn't add more click handlers every time, and instead just run textToSpeech directly.
And you want to move the code to play the chord into the setTimeout of playChord so it doesn't run immediately.

CodePudding user response:

Would it be possible to show the changes here on Stackoverflow for the addEventListener and textToSpeech input? From what I understand, the addEventListener has to be completely moved inside of the setTimeOut which has been done and creates the setTimeOut. Now every time a chord button is clicked, the chord button will.

For example: if the "sus 4" chord button is clicked, the first time the chord button is clicked the textToSpeech will say the chord name twice and after will play the chord sound twice.

The second time the chord button is clicked the textToSpeech will say the chord name four times and after will play the chord sound four times.

Then on the third time the chord button is clicked the textToSpeech will say the chord name six times and after will play the chord sound six times.

  • Related