List of usage examples for javax.sound.sampled AudioInputStream getFormat
public AudioFormat getFormat()
From source file:ClipTest.java
public static void main(String[] args) throws Exception { // specify the sound to play // (assuming the sound can be played by the audio system) File soundFile = new File("../sounds/voice.wav"); AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile); // load the sound into memory (a Clip) DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat()); Clip clip = (Clip) AudioSystem.getLine(info); clip.open(sound);/*from www. j a v a 2s . c o m*/ // due to bug in Java Sound, explicitly exit the VM when // the sound has stopped. clip.addLineListener(new LineListener() { public void update(LineEvent event) { if (event.getType() == LineEvent.Type.STOP) { event.getLine().close(); System.exit(0); } } }); // play the sound clip clip.start(); }
From source file:Main.java
public static void main(String[] argv) throws Exception { AudioInputStream stream = AudioSystem.getAudioInputStream(new File("audiofile")); // From URL// ww w .j a v a 2 s.co m // stream = AudioSystem.getAudioInputStream(new URL( // "http://hostname/audiofile")); AudioFormat format = stream.getFormat(); if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) { format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2, format.getFrameRate(), true); // big endian stream = AudioSystem.getAudioInputStream(format, stream); } DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(), ((int) stream.getFrameLength() * format.getFrameSize())); Clip clip = (Clip) AudioSystem.getLine(info); clip.open(stream); clip.start(); }
From source file:Main.java
public static void main(String[] argv) throws Exception { AudioInputStream stream = AudioSystem.getAudioInputStream(new File("audiofile")); // stream = AudioSystem.getAudioInputStream(new URL( // "http://hostname/audiofile")); AudioFormat format = stream.getFormat(); if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) { format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2, format.getFrameRate(), true); // big endian stream = AudioSystem.getAudioInputStream(format, stream); }/*w w w .jav a2 s.co m*/ SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class, stream.getFormat(), ((int) stream.getFrameLength() * format.getFrameSize())); SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(stream.getFormat()); line.start(); int numRead = 0; byte[] buf = new byte[line.getBufferSize()]; while ((numRead = stream.read(buf, 0, buf.length)) >= 0) { int offset = 0; while (offset < numRead) { offset += line.write(buf, offset, numRead - offset); } } line.drain(); line.stop(); }
From source file:marytts.tools.analysis.CopySynthesis.java
/** * @param args//from w ww .j ava2 s . c o m */ public static void main(String[] args) throws Exception { String wavFilename = null; String labFilename = null; String pitchFilename = null; String textFilename = null; String locale = System.getProperty("locale"); if (locale == null) { throw new IllegalArgumentException("No locale given (-Dlocale=...)"); } for (String arg : args) { if (arg.endsWith(".txt")) textFilename = arg; else if (arg.endsWith(".wav")) wavFilename = arg; else if (arg.endsWith(".ptc")) pitchFilename = arg; else if (arg.endsWith(".lab")) labFilename = arg; else throw new IllegalArgumentException("Don't know how to treat argument: " + arg); } // The intonation contour double[] contour = null; double frameShiftTime = -1; if (pitchFilename == null) { // need to create pitch contour from wav file if (wavFilename == null) { throw new IllegalArgumentException("Need either a pitch file or a wav file"); } AudioInputStream ais = AudioSystem.getAudioInputStream(new File(wavFilename)); AudioDoubleDataSource audio = new AudioDoubleDataSource(ais); PitchFileHeader params = new PitchFileHeader(); params.fs = (int) ais.getFormat().getSampleRate(); F0TrackerAutocorrelationHeuristic tracker = new F0TrackerAutocorrelationHeuristic(params); tracker.pitchAnalyze(audio); frameShiftTime = tracker.getSkipSizeInSeconds(); contour = tracker.getF0Contour(); } else { // have a pitch file -- ignore any wav file PitchReaderWriter f0rw = new PitchReaderWriter(pitchFilename); if (f0rw.contour == null) { throw new NullPointerException("Cannot read f0 contour from " + pitchFilename); } contour = f0rw.contour; frameShiftTime = f0rw.header.skipSizeInSeconds; } assert contour != null; assert frameShiftTime > 0; // The ALLOPHONES data and labels if (labFilename == null) { throw new IllegalArgumentException("No label file given"); } if (textFilename == null) { throw new IllegalArgumentException("No text file given"); } MaryTranscriptionAligner aligner = new MaryTranscriptionAligner(); aligner.SetEnsureInitialBoundary(false); String labels = MaryTranscriptionAligner.readLabelFile(aligner.getEntrySeparator(), aligner.getEnsureInitialBoundary(), labFilename); MaryHttpClient mary = new MaryHttpClient(); String text = FileUtils.readFileToString(new File(textFilename), "ASCII"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mary.process(text, "TEXT", "ALLOPHONES", locale, null, null, baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); DocumentBuilder builder = docFactory.newDocumentBuilder(); Document doc = builder.parse(bais); aligner.alignXmlTranscriptions(doc, labels); assert doc != null; // durations double[] endTimes = new LabelfileDoubleDataSource(new File(labFilename)).getAllData(); assert endTimes.length == labels.split(Pattern.quote(aligner.getEntrySeparator())).length; // Now add durations and f0 targets to document double prevEnd = 0; NodeIterator ni = MaryDomUtils.createNodeIterator(doc, MaryXML.PHONE, MaryXML.BOUNDARY); for (int i = 0; i < endTimes.length; i++) { Element e = (Element) ni.nextNode(); if (e == null) throw new IllegalStateException("More durations than elements -- this should not happen!"); double durInSeconds = endTimes[i] - prevEnd; int durInMillis = (int) (1000 * durInSeconds); if (e.getTagName().equals(MaryXML.PHONE)) { e.setAttribute("d", String.valueOf(durInMillis)); e.setAttribute("end", new Formatter(Locale.US).format("%.3f", endTimes[i]).toString()); // f0 targets at beginning, mid, and end of phone StringBuilder f0String = new StringBuilder(); double startF0 = getF0(contour, frameShiftTime, prevEnd); if (startF0 != 0 && !Double.isNaN(startF0)) { f0String.append("(0,").append((int) startF0).append(")"); } double midF0 = getF0(contour, frameShiftTime, prevEnd + 0.5 * durInSeconds); if (midF0 != 0 && !Double.isNaN(midF0)) { f0String.append("(50,").append((int) midF0).append(")"); } double endF0 = getF0(contour, frameShiftTime, endTimes[i]); if (endF0 != 0 && !Double.isNaN(endF0)) { f0String.append("(100,").append((int) endF0).append(")"); } if (f0String.length() > 0) { e.setAttribute("f0", f0String.toString()); } } else { // boundary e.setAttribute("duration", String.valueOf(durInMillis)); } prevEnd = endTimes[i]; } if (ni.nextNode() != null) { throw new IllegalStateException("More elements than durations -- this should not happen!"); } // TODO: add pitch values String acoustparams = DomUtils.document2String(doc); System.out.println("ACOUSTPARAMS:"); System.out.println(acoustparams); }
From source file:Main.java
/** Read sampled audio data from the specified URL and play it */ public static void streamSampledAudio(URL url) throws IOException, UnsupportedAudioFileException, LineUnavailableException { AudioInputStream ain = null; // We read audio data from here SourceDataLine line = null; // And write it here. try {// w w w . ja va2 s. c o m // Get an audio input stream from the URL ain = AudioSystem.getAudioInputStream(url); // Get information about the format of the stream AudioFormat format = ain.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); // If the format is not supported directly (i.e. if it is not PCM // encoded, then try to transcode it to PCM. if (!AudioSystem.isLineSupported(info)) { // This is the PCM format we want to transcode to. // The parameters here are audio format details that you // shouldn't need to understand for casual use. AudioFormat pcm = new AudioFormat(format.getSampleRate(), 16, format.getChannels(), true, false); // Get a wrapper stream around the input stream that does the // transcoding for us. ain = AudioSystem.getAudioInputStream(pcm, ain); // Update the format and info variables for the transcoded data format = ain.getFormat(); info = new DataLine.Info(SourceDataLine.class, format); } // Open the line through which we'll play the streaming audio. line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); // Allocate a buffer for reading from the input stream and writing // to the line. Make it large enough to hold 4k audio frames. // Note that the SourceDataLine also has its own internal buffer. int framesize = format.getFrameSize(); byte[] buffer = new byte[4 * 1024 * framesize]; // the buffer int numbytes = 0; // how many bytes // We haven't started the line yet. boolean started = false; for (;;) { // We'll exit the loop when we reach the end of stream // First, read some bytes from the input stream. int bytesread = ain.read(buffer, numbytes, buffer.length - numbytes); // If there were no more bytes to read, we're done. if (bytesread == -1) break; numbytes += bytesread; // Now that we've got some audio data, to write to the line, // start the line, so it will play that data as we write it. if (!started) { line.start(); started = true; } // We must write bytes to the line in an integer multiple of // the framesize. So figure out how many bytes we'll write. int bytestowrite = (numbytes / framesize) * framesize; // Now write the bytes. The line will buffer them and play // them. This call will block until all bytes are written. line.write(buffer, 0, bytestowrite); // If we didn't have an integer multiple of the frame size, // then copy the remaining bytes to the start of the buffer. int remaining = numbytes - bytestowrite; if (remaining > 0) System.arraycopy(buffer, bytestowrite, buffer, 0, remaining); numbytes = remaining; } // Now block until all buffered sound finishes playing. line.drain(); } finally { // Always relinquish the resources we use if (line != null) line.close(); if (ain != null) ain.close(); } }
From source file:org.sipfoundry.sipxconfig.site.common.AssetSelector.java
public static boolean isAcceptedAudioFormat(InputStream stream) { try {//from w w w.ja v a2s . c om InputStream testedStream = stream; // HACK: looks like in openjdk InputStream does not support mark/reset if (!stream.markSupported()) { // getAudioInputStream depends on mark reset do we wrap buffered input stream // around passed stream testedStream = new BufferedInputStream(stream); } AudioInputStream audio = AudioSystem.getAudioInputStream(new BufferedInputStream(testedStream)); AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000, // sample // rate 16, // bits per sample 1, // channels 2, // frame rate 8000, // frame size false); // isBigEndian) return format.matches(audio.getFormat()); } catch (IOException e) { LOG.warn("Uploaded file problems.", e); } catch (UnsupportedAudioFileException e) { LOG.info("Unsupported format", e); } return false; }
From source file:it.univpm.deit.semedia.musicuri.core.Toolset.java
/** * Extracts/encodes the AudioSignatureDS for a given audio file * @param file the audio file to encode * @return a string containing the whole XML-formatted MPEG-7 description document *///from w w w. j a v a2s. c o m public static String createMPEG7Description(File file) throws IOException { if (isSupportedAudioFile(file)) { System.out.println("Extracting Query Audio Signature"); String xmlString = null; Config configuration = new ConfigDefault(); configuration.enableAll(false); configuration.setValue("AudioSignature", "enable", true); configuration.setValue("AudioSignature", "decimation", 32); //System.out.println("File: " + file.getName()); AudioInputStream ais = null; try { ais = AudioSystem.getAudioInputStream(file); AudioFormat f = ais.getFormat(); if (f.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) { System.out.println("Converting Audio stream format"); ais = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, ais); f = ais.getFormat(); } String workingDir = getCWD(); String tempFilename = workingDir + "/temp.wav"; AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(tempFilename)); File tmpFile = new File(tempFilename); AudioInFloatSampled audioin = new AudioInFloatSampled(tmpFile); String str = tmpFile.getCanonicalPath(); String[] ar = { str }; //xmlString = Encoder.fromWAVtoXML(ar); // gather information about audio file MP7MediaInformation media_info = new MP7MediaInformation(); media_info.setFileSize(tmpFile.length()); AudioFormat format = audioin.getSourceFormat(); media_info.setSample(format.getSampleRate(), format.getSampleSizeInBits()); media_info.setNumberOfChannels(audioin.isMono() ? 1 : 2); // create mpeg-7 writer MP7Writer mp7writer = new MP7Writer(); mp7writer.setMediaInformation(media_info); // create encoder Encoder encoder = null; Config config = new ConfigDefault(); config.enableAll(false); config.setValue("AudioSignature", "enable", true); config.setValue("AudioSignature", "decimation", 32); encoder = new Encoder(audioin.getSampleRate(), mp7writer, config); //encoder.addTimeElapsedListener(new Ticker(System.err)); // copy audio signal from source to encoder long oldtime = System.currentTimeMillis(); float[] audio; while ((audio = audioin.get()) != null) { if (!audioin.isMono()) audio = AudioInFloat.getMono(audio); encoder.put(audio); } encoder.flush(); System.out.println("Extraction Time : " + (System.currentTimeMillis() - oldtime) + " ms"); // whole MPEG-7 description into a string xmlString = mp7writer.toString(); //System.out.println( xmlString ) } catch (Exception e) { e.printStackTrace(System.err); } finally { //ais.close(); } return xmlString; } else { System.out.println("Unsupported audio file format"); return null; } }
From source file:sx.blah.discord.api.internal.DiscordUtils.java
/** * Converts an {@link AudioInputStream} to 48000Hz 16 bit stereo signed Big Endian PCM format. * * @param stream The original stream./*w w w . jav a 2 s. com*/ * @return The PCM encoded stream. */ public static AudioInputStream getPCMStream(AudioInputStream stream) { AudioFormat baseFormat = stream.getFormat(); //Converts first to PCM data. If the data is already PCM data, this will not change anything. AudioFormat toPCM = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), //AudioConnection.OPUS_SAMPLE_RATE, baseFormat.getSampleSizeInBits() != -1 ? baseFormat.getSampleSizeInBits() : 16, baseFormat.getChannels(), //If we are given a frame size, use it. Otherwise, assume 16 bits (2 8bit shorts) per channel. baseFormat.getFrameSize() != -1 ? baseFormat.getFrameSize() : 2 * baseFormat.getChannels(), baseFormat.getFrameRate() != -1 ? baseFormat.getFrameRate() : baseFormat.getSampleRate(), baseFormat.isBigEndian()); AudioInputStream pcmStream = AudioSystem.getAudioInputStream(toPCM, stream); //Then resamples to a sample rate of 48000hz and ensures that data is Big Endian. AudioFormat audioFormat = new AudioFormat(toPCM.getEncoding(), OpusUtil.OPUS_SAMPLE_RATE, toPCM.getSampleSizeInBits(), toPCM.getChannels(), toPCM.getFrameSize(), toPCM.getFrameRate(), true); return AudioSystem.getAudioInputStream(audioFormat, pcmStream); }
From source file:org.sipfoundry.voicemail.VmMessage.java
/** * Combine two wav files into one bigger one * // w w w .j a v a 2 s .c o m * @param newFile * @param orig1 * @param orig2 * @throws Exception */ static void concatAudio(File newFile, File orig1, File orig2) throws Exception { String operation = "dunno"; try { operation = "getting AudioInputStream from " + orig1.getPath(); AudioInputStream clip1 = AudioSystem.getAudioInputStream(orig1); operation = "getting AudioInputStream from " + orig2.getPath(); AudioInputStream clip2 = AudioSystem.getAudioInputStream(orig2); operation = "building SequnceInputStream"; AudioInputStream concatStream = new AudioInputStream(new SequenceInputStream(clip1, clip2), clip1.getFormat(), clip1.getFrameLength() + clip2.getFrameLength()); operation = "writing SequnceInputStream to " + newFile.getPath(); AudioSystem.write(concatStream, AudioFileFormat.Type.WAVE, newFile); LOG.info("VmMessage::concatAudio created combined file " + newFile.getPath()); } catch (Exception e) { String trouble = "VmMessage::concatAudio Problem while " + operation; // LOG.error(trouble, e); throw new Exception(trouble, e); } }
From source file:tvbrowser.extras.reminderplugin.ReminderPlugin.java
/** * Plays a sound.//www . ja v a 2 s. c o m * * @param fileName * The file name of the sound to play. * @return The sound Object. */ public static Object playSound(final String fileName) { try { if (StringUtils.endsWithIgnoreCase(fileName, ".mid")) { final Sequencer sequencer = MidiSystem.getSequencer(); sequencer.open(); final InputStream midiFile = new FileInputStream(fileName); sequencer.setSequence(MidiSystem.getSequence(midiFile)); sequencer.start(); new Thread("Reminder MIDI sequencer") { @Override public void run() { setPriority(Thread.MIN_PRIORITY); while (sequencer.isRunning()) { try { Thread.sleep(100); } catch (Exception ee) { // ignore } } try { sequencer.close(); midiFile.close(); } catch (Exception ee) { // ignore } } }.start(); return sequencer; } else { final AudioInputStream ais = AudioSystem.getAudioInputStream(new File(fileName)); final AudioFormat format = ais.getFormat(); final DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); if (AudioSystem.isLineSupported(info)) { final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); line.start(); new Thread("Reminder audio playing") { private boolean stopped; @Override public void run() { byte[] myData = new byte[1024 * format.getFrameSize()]; int numBytesToRead = myData.length; int numBytesRead = 0; int total = 0; int totalToRead = (int) (format.getFrameSize() * ais.getFrameLength()); stopped = false; line.addLineListener(new LineListener() { public void update(LineEvent event) { if (line != null && !line.isRunning()) { stopped = true; line.close(); try { ais.close(); } catch (Exception ee) { // ignore } } } }); try { while (total < totalToRead && !stopped) { numBytesRead = ais.read(myData, 0, numBytesToRead); if (numBytesRead == -1) { break; } total += numBytesRead; line.write(myData, 0, numBytesRead); } } catch (Exception e) { } line.drain(); line.stop(); } }.start(); return line; } else { URL url = new File(fileName).toURI().toURL(); AudioClip clip = Applet.newAudioClip(url); clip.play(); } } } catch (Exception e) { e.printStackTrace(); if ((new File(fileName)).isFile()) { URL url; try { url = new File(fileName).toURI().toURL(); AudioClip clip = Applet.newAudioClip(url); clip.play(); } catch (MalformedURLException e1) { } } else { String msg = mLocalizer.msg("error.1", "Error loading reminder sound file!\n({0})", fileName); JOptionPane.showMessageDialog(UiUtilities.getBestDialogParent(MainFrame.getInstance()), msg, Localizer.getLocalization(Localizer.I18N_ERROR), JOptionPane.ERROR_MESSAGE); } } return null; }