-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
156 lines (125 loc) · 4.69 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import {baneTransform} from './audio-transformer';
import {translateEnglishToDeathMetal} from './translate';
const buttonEl = document.querySelector('button')!;
const englishEl = document.querySelector('textarea#english') as HTMLInputElement;
const deathMetalEl = document.querySelector('div#death-metal') as HTMLDivElement;
const openAiKeyEl = document.querySelector('input#openai-key') as HTMLInputElement;
const FADE_TIME = 1;
// Save OpenAI key to localStorage whenever we blur the element.
openAiKeyEl.addEventListener('blur', e => localStorage.setItem('openai_key', openAiKeyEl.value));
document.addEventListener('DOMContentLoaded', () => {
openAiKeyEl.value = localStorage.getItem('openai_key')!;
});
buttonEl.addEventListener('click', main);
const audioContext = new AudioContext();
async function main() {
const english = englishEl.value;
if (!english) {
throw new Error('No text!');
}
startBackingTrack();
deathMetalEl.innerText = '...';
// First translate into death metal english.
const deathMetal = await translateEnglishToDeathMetal(english);
// deathMetalEl.innerText = deathMetal;
const {base64Audio, wordTimings} = await textToSpeechBase64(deathMetal);
console.log(wordTimings);
const words = deathMetal.split(' ');
scheduleWordsAndTimings(words, wordTimings);
const arrayBuffer = base64ToArrayBuffer(base64Audio);
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
const transformedAudioBuffer = await baneTransform(audioBuffer);
playAudioBuffer(transformedAudioBuffer);
stopBackingTrackAfter(transformedAudioBuffer.duration);
}
function scheduleWordsAndTimings(words: string[], wordTimings: number[]) {
if (words.length != wordTimings.length) {
console.warn(`|words| = ${words.length} != |wordTimings| = ${wordTimings.length}`);
}
deathMetalEl.innerText = '';
for (const [ ind, word ] of words.entries()) {
const second = wordTimings[ ind ];
setTimeout(() => {
deathMetalEl.innerText += ` ${word}`;
}, second * 1000);
}
}
interface TTSResults {
base64Audio: string;
wordTimings: number[];
}
async function textToSpeechBase64(text: string): Promise<TTSResults> {
const wordsWithMarks = text.split(' ')
.map((word, index) => `<mark name="${index}"/>${word}`)
.join(' ');
console.log(wordsWithMarks);
const requestParams = {
"audioConfig": {
"audioEncoding": "MP3",
"sampleRateHertz": 16000,
"speakingRate": 0.8,
},
"input": {
// "text": text
"ssml": `<speak>${wordsWithMarks}</speak>`
},
"voice": {
"languageCode": "en-US"
},
"enableTimePointing": [
"SSML_MARK"
]
};
const key = 'AIzaSyDOi68xAua2Jt1M4BR5M8DjNeoyMzSWmuY';
const url = `https://texttospeech.googleapis.com/v1beta1/text:synthesize?alt=json&key=${key}`;
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestParams)
});
const responseJson = await response.json();
console.log(responseJson);
const wordTimings = responseJson.timepoints.map((tp: any) => tp.timeSeconds);
// Base64 encoded speech is here: responseJson.audioContent.
return {base64Audio: responseJson.audioContent, wordTimings};
}
// Cribbed from https://stackoverflow.com/a/21797381
function base64ToArrayBuffer(base64: string) {
var binaryString = atob(base64);
var bytes = new Uint8Array(binaryString.length);
for (var i = 0; i < binaryString.length; i++) {
bytes[ i ] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
function playAudioBuffer(audioBuffer: AudioBuffer) {
// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
const source = audioContext.createBufferSource();
// set the buffer in the AudioBufferSourceNode
source.buffer = audioBuffer;
// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
source.connect(audioContext.destination);
// start the source playing
source.start();
}
const backingAudio = new Audio('backing.mp3');
backingAudio.load();
let gainNode: GainNode;
const source = audioContext.createMediaElementSource(backingAudio);
gainNode = audioContext.createGain();
source.connect(gainNode);
gainNode.connect(audioContext.destination);
function startBackingTrack() {
backingAudio.play();
gainNode.gain.setValueAtTime(0.0, audioContext.currentTime);
gainNode.gain.linearRampToValueAtTime(1.0, audioContext.currentTime + FADE_TIME);
}
function stopBackingTrackAfter(duration: number) {
gainNode.gain.linearRampToValueAtTime(1.0, audioContext.currentTime + duration);
gainNode.gain.linearRampToValueAtTime(0.0, audioContext.currentTime + duration + FADE_TIME);
}