Created
February 6, 2019 17:24
-
-
Save loraxx753/c45b6bb38baa359805f2d4f715ef3cdb to your computer and use it in GitHub Desktop.
File for playing mp3's or using speech synthesis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** USAGE | |
import { speak, createSound } from './synth.js'; | |
(async () => { | |
document.querySelector('button[start-static]').addEventListener('click', () => { | |
const sound = createSound("a.mp3"); | |
sound.play() | |
}) | |
document.querySelector('button[start-song]').addEventListener('click', () => { | |
const sound = createSound("/b.mp3"); | |
sound.play() | |
}) | |
document.querySelector('button[start-speech]').addEventListener('click', () => { | |
speak({ text:"1. 5. 7. 3. 4. 2. 5. 6. 7.", pitch: 0.4, rate: 0.9, volume: 1}) | |
}) | |
})() | |
**/ | |
export const speak = async ({text = "The revolution will not be televised", pitch=.75, rate=1, volume=50, lang="en-US", voice="english-us espeak"}) => { | |
let ttsRecorder = new SpeechSynthesisRecorder({ | |
text, | |
utteranceOptions: { | |
voice, | |
lang, | |
pitch, | |
rate, | |
volume, | |
} | |
}); | |
ttsRecorder.start() | |
.then(tts => tts.mediaSource()) | |
.then(({tts, data}) => { | |
// console.log(tts, data); | |
// `data` : `MediaSource` | |
tts.audioNode.srcObj = data; | |
console.log('audio node', tts.audioNode) | |
tts.audioNode.title = tts.utterance.text; | |
tts.audioNode.onloadedmetadata = () => { | |
// console.log(tts.audioNode.duration); | |
tts.audioNode.play(); | |
} | |
}) | |
} | |
export const createSound = (mp3File) => { | |
var audioTag = new Audio(); | |
// audioTag.toggleAttribute('autoplay') | |
var audioSource = document.createElement("source"); | |
audioTag.type = "audio/mpeg"; | |
audioTag.src = mp3File; | |
audioTag.appendChild(audioSource); | |
return audioTag | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment