How to have the control over the audio playing when text is converted to speech using Azure Speech Service?

Shivani V 0 Reputation points
2024-07-08T06:17:54.4566667+00:00

Below is the code I am using to convert text to audio for a button click using Azure speech service, but I am unable to stop the audio that is playing,
I would like to use the same button to stop the audio while it is playing.
How to have the control over the audio that is playing.

const speechConfig = SpeechSDK.SpeechConfig.fromSubscription("key", "region");

let synthesizer = null;

function initializeSynthesizer() {

 const audioConfig = SpeechSDK.AudioConfig.fromDefaultSpeakerOutput();

 synthesizer = new SpeechSDK.SpeechSynthesizer(speechConfig, audioConfig);

 synthesizer.synthesizing = (s, e) => {

     console.log(`Synthesizing: ${e.result.audioData.byteLength} bytes`);

 };

}

function convertTextToSpeech(text) {

 if (!synthesizer) {

     initializeSynthesizer();

 }

 let selectedLanguage = TranslationModule.getSelectedLanguage(); // Assuming TranslationModule handles language selection

 TranslationModule.translateText(text, selectedLanguage).then(translatedText => {

     synthesizer.speakTextAsync(

         translatedText,

         result => {

             if (result.reason === SpeechSDK.ResultReason.SynthesizingAudioCompleted) {

                 console.log("Speech synthesis completed.");

             } else {

                 console.error("Speech synthesis canceled, " + result.errorDetails);

             }

         },

         error => {

             console.error("Error during speech synthesis:", error);

         }

     );

     console.log("Speech synthesis started:", text); // Log synthesis started

 }).catch(error => {

     console.error('Error translating text for speech:', error);

 });

}

$(document).off('click').on('click', '#btnread', function () {

 let textToRead = this.getAttribute('data-text'); // Assuming the button has a 'data-text' attribute with the text to read

 convertTextToSpeech(textToRead);

});

Azure AI Speech
Azure AI Speech
An Azure service that integrates speech processing into apps and services.
1,789 questions
Azure Translator
Azure Translator
An Azure service to easily conduct machine translation with a simple REST API call.
417 questions
Azure OpenAI Service
Azure OpenAI Service
An Azure service that provides access to OpenAI’s GPT-3 models with enterprise capabilities.
3,275 questions
Azure AI services
Azure AI services
A group of Azure services, SDKs, and APIs designed to make apps more intelligent, engaging, and discoverable.
2,918 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.