Code viewer for World: Text-to-speech "Hello World"
CHAT_KEY = "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"
GOOGLE_KEY = "AIzaSyCXQny4ElmR6rtm04v7QNGdPzDhJHSDzdc"

document.write ( `
<h1> API Hello World </h1>
<p>
This is an example API call for both GPT 3.5 turbo and Google Cloud TTS AI API. Outputs to console.
</p>
<button id="gptButton">GPT 3.5-turbo</button>
<button id="googleButton">Google Cloud TTS</button>
` );

$(document).ready(function() {
 $("#gptButton").click(function() {
   $.ajax({
       url: 'https://api.openai.com/v1/chat/completions',
       type: 'POST',
       headers: {
           'Authorization': 'Bearer ' + CHAT_KEY
       },
       data: JSON.stringify({
           "model": "gpt-3.5-turbo",
           "messages": [
             {
               "role": "system",
               "content": "You are a helpful assistant."
             },
             {
               "role": "user",
               "content": "Hello World!"
             }
           ],
           "max_tokens": 150
       }),
       contentType: 'application/json',
       success: function(data) {
           console.log(data.choices[0].message.content);
       }
   });
 });

 $("#googleButton").click(function() {
   $.ajax({
       url: 'https://texttospeech.googleapis.com/v1/text:synthesize?key=' + GOOGLE_KEY,
       type: 'POST',
       data: JSON.stringify({
          'input': {
             'text': "Hello World!"
          },
          'voice': {
             'languageCode': 'en-GB',
             'name': 'en-GB-Studio-B',
             'ssmlGender': 'MALE'
          },
          'audioConfig': {
             'audioEncoding': 'LINEAR16',
             'speakingRate': "1",
             "pitch": "0"
          }
       }),
       contentType: 'application/json',
       success: function (response) {
          // Response is encoded audio, so we decode it and output it to the console.
          var audioData = atob(response.audioContent);
          var audioArray = new Uint8Array(audioData.length);
          for (var i = 0; i < audioData.length; i++) {
             audioArray[i] = audioData.charCodeAt(i);
          }
          var audioBuffer = new ArrayBuffer(audioArray.length);
          var bufferView = new Uint8Array(audioBuffer);
          for (var i = 0; i < audioArray.length; i++) {
             bufferView[i] = audioArray[i];
          }
          var audioCtx = new AudioContext();
          audioCtx.decodeAudioData(audioBuffer, function (buffer) {
             console.log(buffer);
          });
       },
       error: function (error) {
          console.log('Error', error);
       }
   });
 });
});