0

I am trying to listen to a dynamic file inside a webapp application with audio HTML tag, but i can´t save my file inside the correct folder ...

Here is my file structure inside eclipse, i want to find the path to the audio folder that is selected without hardcoding it:

enter image description here

I can run code on Controller.java, where i add: 1)The html tag :

<audio controls><source src=\"audio/hello.wav\" type=\"audio/wav\"></audio>

2)In order to create my file, i am using

    file = new File("/Users/miguelenrile/Desktop/universidad ICAI/master-teleco-1/Primer cuatri/Arq.servicios.de.red/practicas/P10/asrTomcatEjemploCloudant/src/main/webapp/audio/hello2.wav");

Which is clearly a hardcoded one that won`t work once the directory system changes.

My problem is that i need to find this path, but when searching on the internet how to do it, i never get that path, but instead, something among these lines:

/Users/miguelenrile/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/asrTomcatEjemploCloudant/

which will work when pasted into the browser, but won´t create the file where the audio src expects to find it, so it won´t work...

What i have tried to get the path mentioned before...:

System.out.println("probada: " +getServletContext().getAttribute(ServletContext.TEMPDIR));
System.out.println(getServletContext().getContextPath());
System.out.println(getServletContext().getRealPath(dir));
System.out.println(new File(".").getCanonicalPath());
System.out.println(System.getProperty("user.dir"));
System.out.println(System.getProperty("user.home"));      
System.out.println(this.getClass().getProtectionDomain().getCodeSource().getLocation());
System.out.println(getServletContext().getRealPath("/"));
System.out.println(request.getSession().getServletContext().getRealPath("/"));
System.out.println(request.getContextPath());

All of these formulas will go into here:

/Users/miguelenrile/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/asrTomcatEjemploCloudant/

not into the before mentioned harcoded path ...

I don't know whether i'm missing something...

To sum up:

The path i want to get:

/Users/miguelenrile/Desktop/universidad ICAI/master-teleco-1/Primer cuatri/Arq.servicios.de.red/practicas/P10/asrTomcatEjemploCloudant/src/main/webapp/audio/hello2.wav

The path i am getting:

/Users/miguelenrile/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/asrTomcatEjemploCloudant/

Thanks

Full code:

Controller.java protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("");

    CloudantPalabraStore store = new CloudantPalabraStore();
    System.out.println(request.getServletPath());
    switch(request.getServletPath())
    {
        case "/listar":
            if(store.getDB() == null)
                  out.println("No hay DB");
            else
                out.println("Palabras en la BD Cloudant:<br />" + store.getAll());
            break;

        case "/hablar":
            //Get tghe word to translate with IBM text to Speech
            String text = request.getParameter("palabra");
            String dir = System.getProperty("user.dir");
            System.out.println("current dir = " + dir);

           /*
            System.out.println("probada: " +getServletContext().getAttribute(ServletContext.TEMPDIR));
            System.out.println(getServletContext().getContextPath());
            System.out.println(getServletContext().getRealPath(dir));
            System.out.println(new File(".").getCanonicalPath());
            System.out.println(System.getProperty("user.dir"));
            System.out.println(System.getProperty("user.home"));
            System.out.println(this.getClass().getProtectionDomain().getCodeSource().getLocation());
            System.out.println(getServletContext().getRealPath("/"));
            System.out.println(request.getSession().getServletContext().getRealPath("/"));
            System.out.println(request.getContextPath());
            */


            String path = TextoAPalabras.hablar(text,getServletContext());
            System.out.println("Path que recibo en :" +path);
            out.println("<META HTTP-EQUIV=\"CACHE-CONTROL\" CONTENT=\"NO-CACHE\">");
            out.println("<audio controls><source src=\"audio/hello.wav\" type=\"audio/wav\"></audio>");
            out.println("<p>path del file: "+path +"</p> ");
            break;

        case "/insertar":
            Palabra palabra = new Palabra();
            String parametro = request.getParameter("palabra");

            if(parametro==null)
            {
                out.println("usage: /insertar?palabra=palabra_a_traducir");
            }
            else
            {
                if(store.getDB() == null) 
                {
                    out.println(String.format("Palabra: %s", palabra));
                }
                else
                {
                    parametro = Traductor.translate(parametro, "es", "en", false);
                    palabra.setName(parametro);
                    store.persist(palabra);
                    out.println(String.format("Almacenada la palabra: %s", palabra.getName()));                   
                }
            }
            break;
    }
    out.println("</html>");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}

}

TextoAPalabras.java: Where the file is created

public class TextoAPalabras {

private static File FILE;

public  static String hablar(String text, ServletContext sc) {

//autenticación en el servicio de TextToSpeech;
IamAuthenticator authenticator = new IamAuthenticator("xxxxyyyyy");
TextToSpeech textToSpeech = new TextToSpeech(authenticator);

textToSpeech.setServiceUrl("https://gateway-lon.watsonplatform.net/text-to-speech/api");
//Tenemos certificado así que no es necesario disable SSL certificates
  File file = null;
try {
     file = new File("/Users/miguelenrile/Desktop/universidad ICAI/master-teleco-1/Primer cuatri/Arq.servicios.de.red/practicas/P10/asrTomcatEjemploCloudant/src/main/webapp/audio/hello2.wav");

      SynthesizeOptions synthesizeOptions =
        new SynthesizeOptions.Builder()
          .text(text)
          .accept("audio/wav")
          .voice("en-US_AllisonVoice")
          .build();




      InputStream inputStream = textToSpeech.synthesize(synthesizeOptions).execute().getResult();
      InputStream in = WaveUtils.reWriteWaveHeader(inputStream);
      copyInputStreamToFile(in,file);

      Clip clip = AudioSystem.getClip();
      System.out.println("Devuelvo el file path");
      System.out.println(file.toString());



      in.close();
      inputStream.close();

    } catch (Exception e) {
      e.printStackTrace();
    }

return file.getAbsolutePath();

}
// InputStream -> File
private static void copyInputStreamToFile(InputStream inputStream, File file) 
    throws IOException {

    try (FileOutputStream outputStream = new FileOutputStream(file)) {

        int read;
        byte[] bytes = new byte[1024];

        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }

        // commons-io
        //IOUtils.copy(inputStream, outputStream);

    }
}

}

miguelik
  • 475
  • 4
  • 11

1 Answers1

0

Using getRealPath() with the document root path for the audio file as the parameter should hand you the actual path to your file.

getServletContext().getRealPath("/audio/hello.wav");
TheSlavMan
  • 44
  • 8