List of usage examples for javax.sound.sampled AudioSystem write
public static int write(final AudioInputStream stream, final AudioFileFormat.Type fileType, final File out) throws IOException
From source file:marytts.signalproc.effects.VocalTractLinearScalerEffect.java
/** * Command line interface to the vocal tract linear scaler effect. * //from w w w . j a v a 2 s.com * @param args the command line arguments. Exactly two arguments are expected: * (1) the factor by which to scale the vocal tract (between 0.25 = very long and 4.0 = very short vocal tract); * (2) the filename of the wav file to modify. * Will produce a file basename_factor.wav, where basename is the filename without the extension. * @throws Exception if processing fails for some reason. */ public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println( "Usage: java " + VocalTractLinearScalerEffect.class.getName() + " <factor> <filename>"); System.exit(1); } float factor = Float.parseFloat(args[0]); String filename = args[1]; AudioDoubleDataSource input = new AudioDoubleDataSource( AudioSystem.getAudioInputStream(new File(filename))); AudioFormat format = input.getAudioFormat(); VocalTractLinearScalerEffect effect = new VocalTractLinearScalerEffect((int) format.getSampleRate()); DoubleDataSource output = effect.apply(input, "amount:" + factor); DDSAudioInputStream audioOut = new DDSAudioInputStream(output, format); String outFilename = FilenameUtils.removeExtension(filename) + "_" + factor + ".wav"; AudioSystem.write(audioOut, AudioFileFormat.Type.WAVE, new File(outFilename)); System.out.println("Created file " + outFilename); }
From source file:com.octo.captcha.module.web.sound.SoundToWavHelper.java
/** * retrieve a new SoundCaptcha using SoundCaptchaService and flush it to the response. <br/> Captcha are localized * using request locale. <br/>This method returns a 404 to the client instead of the image if the request isn't * correct (missing parameters, etc...).. <br/>The log may be null. <br/> * * @param theRequest the request/*from www .j a va 2s .c o m*/ * @param theResponse the response * @param log a commons logger * @param service an SoundCaptchaService instance * * @throws java.io.IOException if a problem occurs during the jpeg generation process */ public static void flushNewCaptchaToResponse(HttpServletRequest theRequest, HttpServletResponse theResponse, Log log, SoundCaptchaService service, String id, Locale locale) throws IOException { // call the ImageCaptchaService method to retrieve a captcha byte[] captchaChallengeAsWav = null; ByteArrayOutputStream wavOutputStream = new ByteArrayOutputStream(); try { AudioInputStream stream = service.getSoundChallengeForID(id, locale); // call the ImageCaptchaService method to retrieve a captcha AudioSystem.write(stream, AudioFileFormat.Type.WAVE, wavOutputStream); //AudioSystem.(pAudioInputStream, AudioFileFormat.Type.WAVE, pFile); } catch (IllegalArgumentException e) { // log a security warning and return a 404... if (log != null && log.isWarnEnabled()) { log.warn("There was a try from " + theRequest.getRemoteAddr() + " to render an captcha with invalid ID :'" + id + "' or with a too long one"); theResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } catch (CaptchaServiceException e) { // log and return a 404 instead of an image... if (log != null && log.isWarnEnabled()) { log.warn( "Error trying to generate a captcha and " + "render its challenge as JPEG", e); } theResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } captchaChallengeAsWav = wavOutputStream.toByteArray(); // render the captcha challenge as a JPEG image in the response theResponse.setHeader("Cache-Control", "no-store"); theResponse.setHeader("Pragma", "no-cache"); theResponse.setDateHeader("Expires", 0); theResponse.setContentType("audio/x-wav"); ServletOutputStream responseOutputStream = theResponse.getOutputStream(); responseOutputStream.write(captchaChallengeAsWav); responseOutputStream.flush(); responseOutputStream.close(); }
From source file:org.snitko.app.record.SoundRecorder.java
/** * Captures the sound and record into a WAV file */// w ww . ja va 2s .c o m public void record(File waveFile, final long durationInSeconds) throws LineUnavailableException, IOException { AudioInputStream audioInputStream = record(durationInSeconds); AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, waveFile); }
From source file:com.octo.captcha.module.acegi.JCaptchaSoundController.java
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse response) throws Exception { byte[] captchaChallengeAsWav = null; ByteArrayOutputStream wavOutputStream = new ByteArrayOutputStream(); //get the session id that will identify the generated captcha. //the same id must be used to validate the response, the session id is a good candidate! String captchaId = httpServletRequest.getSession().getId(); AudioInputStream challenge = soundCaptchaService.getSoundChallengeForID(captchaId, httpServletRequest.getLocale()); // a jpeg encoder AudioInputStream stream = (AudioInputStream) challenge; // call the ImageCaptchaService method to retrieve a captcha AudioSystem.write(stream, AudioFileFormat.Type.WAVE, wavOutputStream); captchaChallengeAsWav = wavOutputStream.toByteArray(); // configure cache directives response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); //flush content in the response response.setContentType("audio/x-wav"); ServletOutputStream responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaChallengeAsWav); responseOutputStream.flush();/*from ww w. j ava 2s .co m*/ responseOutputStream.close(); return null; }
From source file:org.sipfoundry.voicemail.EmailFormatterTest.java
private void makeWaves(File wavFile, byte filler, int length) throws IOException { byte[] fill = new byte[length]; for (int i = 0; i < length; i++) { fill[i] = filler;/*from w ww .ja va 2 s . c o m*/ } AudioInputStream ais = new AudioInputStream(new ByteArrayInputStream(fill), new AudioFormat(8000, 16, 1, true, false), fill.length); AudioSystem.write(ais, AudioFileFormat.Type.WAVE, wavFile); }
From source file:com.gameminers.mav.firstrun.TeachSphinxThread.java
@Override public void run() { try {/*from w ww. j a v a2 s. c om*/ File training = new File(Mav.configDir, "training-data"); training.mkdirs(); while (Mav.silentFrames < 30) { sleep(100); } Mav.listening = true; InputStream prompts = ClassLoader.getSystemResourceAsStream("resources/sphinx/train/arcticAll.prompts"); List<String> arctic = IOUtils.readLines(prompts); IOUtils.closeQuietly(prompts); Mav.audioManager.playClip("listen1"); byte[] buf = new byte[2048]; int start = 0; int end = 21; AudioInputStream in = Mav.audioManager.getSource().getAudioInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (true) { for (int i = start; i < end; i++) { baos.reset(); String prompt = arctic.get(i); RenderState.setText("\u00A7LRead this aloud:\n" + Fonts.wrapStringToFit( prompt.substring(prompt.indexOf(':') + 1), Fonts.base[1], Display.getWidth())); File file = new File(training, prompt.substring(0, prompt.indexOf(':')) + ".wav"); file.createNewFile(); int read = 0; while (Mav.silentListenFrames > 0) { read = Mav.audioManager.getSource().getAudioInputStream().read(buf); } baos.write(buf, 0, read); while (Mav.silentListenFrames < 60) { in.read(buf); if (read == -1) { RenderState.setText( "\u00A7LAn error occurred\nUnexpected end of stream\nPlease restart Mav"); RenderState.targetHue = 0; return; } baos.write(buf, 0, read); } AudioSystem.write(new AudioInputStream(new ByteArrayInputStream(baos.toByteArray()), in.getFormat(), baos.size() / 2), AudioFileFormat.Type.WAVE, file); Mav.audioManager.playClip("notif2"); } Mav.ttsInterface.say(Mav.phoneticUserName + ", that should be enough for now. Do you want to keep training anyway?"); RenderState.setText("\u00A7LOkay, " + Mav.userName + "\nI think that should be\nenough. Do you want to\nkeep training anyway?\n\u00A7s(Say 'Yes' or 'No' out loud)"); break; //start = end+1; //end += 20; } } catch (Exception e) { e.printStackTrace(); } }
From source file:marytts.server.http.AudioStreamNHttpEntity.java
/** * Wait for the SharedOutputBuffer to become available, write audio data to it. *///from ww w . jav a 2 s . co m public void run() { this.logger = MaryUtils.getLogger(Thread.currentThread().getName()); // We must wait until produceContent() is called: while (out == null) { synchronized (mutex) { try { mutex.wait(); } catch (InterruptedException e) { } } } assert out != null; ContentOutputStream outStream = new ContentOutputStream(out); try { AudioSystem.write(audio, audioType, outStream); outStream.flush(); outStream.close(); logger.info("Finished writing output"); } catch (IOException ioe) { logger.info("Cannot write output, client seems to have disconnected. ", ioe); maryRequest.abort(); } }
From source file:marytts.tools.perceptiontest.AudioStreamNHttpEntity.java
/** * Wait for the SharedOutputBuffer to become available, write audio data to it. *///ww w.j ava2s .co m public void run() { this.logger = MaryUtils.getLogger(Thread.currentThread().getName()); // We must wait until produceContent() is called: while (out == null) { synchronized (mutex) { try { mutex.wait(); } catch (InterruptedException e) { } } } assert out != null; ContentOutputStream outStream = new ContentOutputStream(out); try { AudioSystem.write(audio, audioType, outStream); outStream.flush(); outStream.close(); logger.info("Finished writing output"); } catch (IOException ioe) { logger.info("Cannot write output, client seems to have disconnected. ", ioe); System.err.println("Cannot write output, client seems to have disconnected." + ioe); maryRequest.abort(); } }
From source file:it.sardegnaricerche.voiceid.sr.VCluster.java
public void trimSegments(File inputFile) throws IOException { String base = Utils.getBasename(inputFile); File mydir = new File(base); mydir.mkdirs();//from w w w .j a v a2 s . c o m String mywav = mydir.getAbsolutePath() + "/" + this.getLabel() + ".wav"; AudioFileFormat fileFormat = null; AudioInputStream inputStream = null; AudioInputStream shortenedStream = null; AudioInputStream current = null; int bytesPerSecond = 0; long framesOfAudioToCopy = 0; wavFile = new File(mywav); try { fileFormat = AudioSystem.getAudioFileFormat(inputFile); AudioFormat format = fileFormat.getFormat(); boolean firstTime = true; for (VSegment s : this.getSegments()) { bytesPerSecond = format.getFrameSize() * (int) format.getFrameRate(); inputStream = AudioSystem.getAudioInputStream(inputFile); inputStream.skip(0); inputStream.skip((int) (s.getStart() * 100) * bytesPerSecond / 100); framesOfAudioToCopy = (int) (s.getDuration() * 100) * (int) format.getFrameRate() / 100; if (firstTime) { shortenedStream = new AudioInputStream(inputStream, format, framesOfAudioToCopy); } else { current = new AudioInputStream(inputStream, format, framesOfAudioToCopy); shortenedStream = new AudioInputStream(new SequenceInputStream(shortenedStream, current), format, shortenedStream.getFrameLength() + framesOfAudioToCopy); } firstTime = false; } AudioSystem.write(shortenedStream, fileFormat.getType(), wavFile); } catch (Exception e) { logger.severe(e.getMessage()); e.printStackTrace(); } finally { if (inputStream != null) try { inputStream.close(); } catch (Exception e) { logger.severe(e.getMessage()); } if (shortenedStream != null) try { shortenedStream.close(); } catch (Exception e) { logger.severe(e.getMessage()); } if (current != null) try { current.close(); } catch (Exception e) { logger.severe(e.getMessage()); } } logger.fine("filename: " + wavFile.getAbsolutePath()); }
From source file:com.github.woz_dialog.ros_woz_dialog_project.TTSHTTPClient.java
public static void generateFile(byte[] data, File outputFile) { try {/*from ww w . j ava2s .c o m*/ AudioInputStream audioStream = getAudioStream(data); if (outputFile.getName().endsWith("wav")) { int nb = AudioSystem.write(audioStream, AudioFileFormat.Type.WAVE, new FileOutputStream(outputFile)); log.fine("WAV file written to " + outputFile.getCanonicalPath() + " (" + (nb / 1000) + " kB)"); } else { throw new RuntimeException("Unsupported encoding " + outputFile); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("could not generate file: " + e); } }