Bluemix: Response of Text-to-speech is not playing

2019-08-08 16:57发布

问题:

Can you help met solve this issue, why the response of Text-to-speech is not playing audio using below code?

index.jsp

$.fn.PlayBtnClicked = function() { 
    var txt=$(this).data("text"); 
    $.ajax({
      type: "GET",
      url: 'demo',async: false,
      data: { text: txt} ,
        success: function(response) { 
        $(".result").show();
            var audio = document.getElementById("myAudio"); 
            audio.src = response;
            audio.type = "type/ogg"; 
            audio.play();
        }
     });
 }; 

<audio id="myAudio" autoplay preload="auto" autobuffer controls class="audio"></audio>

DemoServlet.java

protected void doGet(final HttpServletRequest req,
            final HttpServletResponse resp) throws ServletException,
            IOException {
        String serviceName = "text_to_speech";

        // If running locally complete the variables below with the information
        // in VCAP_SERVICES
        String baseURL = "https://stream.watsonplatform.net/text-to-speech/api";
        String username = "USERNAME";
        String password = "PASSWORD";

        if (req.getParameter("text") == null) {
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
        } else {
            boolean download = false;
            if (req.getParameter("download") != null
                    && req.getParameter("download").equalsIgnoreCase("true")) {
                download = true;
            } 
            req.setCharacterEncoding("UTF-8");
            try { 
                String  text=req.getParameter("text");
                text=URLEncoder.encode(text, "UTF-8");
                String voice="&voice=en-US_AllisonVoice";
                String queryStr=text+voice;
                String url = baseURL + "/v1/synthesize";
                if (queryStr != null) {
                    url += "?text=" + queryStr;
                }
                URI uri = new URI(url).normalize();

                Request newReq = Request.Get(uri);
                newReq.addHeader("Accept", "audio/ogg; codecs=opus");

                Executor executor = Executor.newInstance().auth(username,
                        password);
                Response response = executor.execute(newReq);
                if (download) {
                    resp.setHeader("content-disposition",
                            "attachment; filename=transcript.ogg");
                }
                ServletOutputStream servletOutputStream = resp
                        .getOutputStream();
                response.returnResponse().getEntity()
                        .writeTo(servletOutputStream);
                servletOutputStream.flush();
                servletOutputStream.close();
            } catch (Exception e) {
                // Log something and return an error message
                logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
                resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
            }
        }
    }

Here both the java moethod runs successfully in response it returns some binary kind of data to jsp , ajax response. But still i could not play the audio. Could you please help me to solve out this issue?

回答1:

The problem is that you are setting an html response to the src property of an <audio> tag.

You need to do something like:

$.fn.PlayBtnClicked = function() { 
  var text = $(this).data("text"); 

  var audio = document.getElementById("myAudio");
  audio.setAttribute('src','/synthesize?text=' + encodeURIComponent(text));
});

More info

  • audio tag
  • IBM Watson Text to Speech