Search code examples
node.jstext-to-speechibm-watson

404 error when using Jade/Pug to output audio on a webpage


I am trying to use the IBM Watson Text to Speech api through a webpage. On the webpage I have a form that takes the sentence or word the user wants to have read and a button "SPEAK!" that finalizes and reads the form input. My issue is that when I am looking in the console to make sure everything is going smoothly I see that my audio file is not being found.

App.js -- this is the code that connects to the api and then sends the synthesized code to "audioFiles/Output.ogg" where they can be accessed.

var input;
app.get("/speech", function(req, res, next) {
 input = req.query.speech;
 const TextToSpeechV1 = require('watson-developer-cloud/text-to-speech/v1');
 const fs = require('file-system');
 if(input) {
   var intentValNumber = input.length;
 }
 console.log(intentValNumber);
 if (intentValNumber > 0) {
   const text_to_speech = new TextToSpeechV1({
       url: "URL is here",
       username: 'UserName is here',
       password: 'PassWord is here',
       version_date: TextToSpeechV1.VERSION_DATE_2017_04_26
     });
     var params = {
       text: input,
       voice: 'en-US_MichaelVoice',
       accept: 'audio/ogg'
     };
     console.log(input);
  // Pipe the synthesized text to a file.
   text_to_speech.synthesize(params).on('error', function(error) {
     console.log('Error:', error);
   }).pipe(fs.createWriteStream('audioFiles/output.ogg'));
 };
next();
});

speech.pug -- this is where the form and the audio should be performed.

extends layout

block content
 .main.container.row
  .col-md-6.col-md-offset-3
    h1.display-4.m-b-2 Magic Reading!
     form(method="GET" action="/speech")
      div.form-group
       label(for='speech') Type something to be spoken:
       input#speech.form-control(type='text', placeholder='Type something to be read' name='speech')
       button.btn.btn-primary(type='submit') SPEAK!
       audio(controls='', autoplay='')
         source(src='../audioFiles/output.ogg', type='audio/ogg')

Specific error - GET http://localhost:3000/audioFiles/output.ogg

Thanks in advance for any advice! Also let me know if anyone needs more information about the error or code.

EDIT -- this is a simplified version of my directory structure...

 Project
  |
  +-- audioFiles(folder)
  |   |
  |   + - output.ogg
  |   + - music.mp3
  |
  +-- public(folder)
  |     |
  |     + - images(folder)
  |     + - stylesheets(folder)
  |    
  +-- routes(folder)
  |    |  
  |    +-- index.js
  |    
  +-- views(folder)
  |    |  
  |    +-- speech.pug
  |    
  + -- app.js

Solution

  • Add the following line in your app.js

    app.use("/audioFiles", express.static(path.join(__dirname, "audioFiles")))

    Then, http://localhost:3000/audioFiles/output.ogg shouldn't give 404 error.