javascriptnode.jsaudioejsgtts

"I want to play received audio within my Node server without relying on external applications for playback, currently,


The method I am currently relying on uses an external application for playing Audio files but I want to play the sound straight in the browser without using any additional application, what are the better lightweight options I should adopt?

I am currently playing sound using this

    // setup txt to speach    
    var question = result.data.que;
    var reply = result.data.ans;

    const  gtts = new gTTS(question, 'en');
    const  gttr = new gTTS(reply, 'en');

    // text to speach conversion
    gtts.save("question.mp3", function (err, result){
        if(err) { throw new Error(err); }
        console.log("Text to speech converted!");
    });

    gttr.save("reply.mp3", function (err, result){
        if(err) { throw new Error(err); }
        console.log("Text to speech converted!");
    });

    
    // playing sound 
    const player = playsound();
    
    const soundPath1 = './question.mp3';
    player.play(soundPath1, (err) => {
        if (err) {
            console.error('Error playing sound:', err);
        }
    });

 const player2 = playsound();
    const soundPath2 = './reply.mp3';
    player2.play(soundPath2, (err) => {
        if (err) {
            console.error('Error playing sound:', err);
        }
    });


Solution

  • const audio = new Audio();
    function playSound(sound){
        audio.src = sound;
        audio.play();
    }
    <button onclick="playSound('question.mp3')"> Track1 </button>
    <button onclick="playSound('reply.mp3')"> Track2 </button>