List of usage examples for javax.sound.sampled AudioSystem getAudioInputStream
public static AudioInputStream getAudioInputStream(final File file) throws UnsupportedAudioFileException, IOException
From source file:com.player.BasicMP3Player.java
/** * Inits Audio ressources from InputStream. *///ww w . j av a2s . com private void initAudioInputStream(InputStream inputStream) throws UnsupportedAudioFileException, IOException { m_audioInputStream = AudioSystem.getAudioInputStream(inputStream); m_audioFileFormat = AudioSystem.getAudioFileFormat(inputStream); }
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 av a 2s . c om*/ 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:BasicPlayer.java
/** * Inits Audio ressources from file./*from w w w .j av a 2 s . c o m*/ */ protected void initAudioInputStream(File file) throws UnsupportedAudioFileException, IOException { m_audioInputStream = AudioSystem.getAudioInputStream(file); m_audioFileFormat = AudioSystem.getAudioFileFormat(file); }
From source file:BasicPlayer.java
/** * Inits Audio ressources from URL.// w w w. j a v a 2 s . com */ protected void initAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { m_audioInputStream = AudioSystem.getAudioInputStream(url); m_audioFileFormat = AudioSystem.getAudioFileFormat(url); }
From source file:io.github.jeremgamer.editor.panels.MusicFrame.java
public MusicFrame(JFrame frame, final GeneralSave gs) { ArrayList<BufferedImage> icons = new ArrayList<BufferedImage>(); try {/*w w w . ja va 2 s. c om*/ icons.add(ImageIO.read(ImageGetter.class.getResource("icon16.png"))); icons.add(ImageIO.read(ImageGetter.class.getResource("icon32.png"))); icons.add(ImageIO.read(ImageGetter.class.getResource("icon64.png"))); icons.add(ImageIO.read(ImageGetter.class.getResource("icon128.png"))); } catch (IOException e1) { e1.printStackTrace(); } this.setIconImages((List<? extends Image>) icons); this.setTitle("Musique"); this.setSize(new Dimension(300, 225)); this.addWindowListener(new WindowListener() { @Override public void windowActivated(WindowEvent event) { } @Override public void windowClosed(WindowEvent event) { } @Override public void windowClosing(WindowEvent event) { try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } if (clip != null) { clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void windowDeactivated(WindowEvent event) { } @Override public void windowDeiconified(WindowEvent event) { } @Override public void windowIconified(WindowEvent event) { } @Override public void windowOpened(WindowEvent event) { } }); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS)); this.setModal(true); this.setLocationRelativeTo(frame); JPanel properties = new JPanel(); properties.setBorder(BorderFactory.createTitledBorder("Lecture")); ButtonGroup bg = new ButtonGroup(); bg.add(one); bg.add(loop); one.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent event) { JRadioButton rb = (JRadioButton) event.getSource(); if (rb.isSelected()) { gs.set("music.reading", 0); try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } if (clip != null) { if (clip.isRunning()) clip.loop(0); } } } }); loop.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent event) { JRadioButton rb = (JRadioButton) event.getSource(); if (rb.isSelected()) { gs.set("music.reading", 1); try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } if (clip != null) { if (clip.isRunning()) clip.loop(Clip.LOOP_CONTINUOUSLY); } } } }); properties.add(one); properties.add(loop); if (gs.getInt("music.reading") == 0) { one.setSelected(true); } else { loop.setSelected(true); } volume.setMaximum(100); volume.setMinimum(0); volume.setValue(30); volume.setPaintTicks(true); volume.setPaintLabels(true); volume.setMinorTickSpacing(10); volume.setMajorTickSpacing(20); volume.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent event) { JSlider slider = (JSlider) event.getSource(); double value = slider.getValue(); gain = value / 100; dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0); if (clip != null) gainControl.setValue(dB); gs.set("music.volume", (int) value); } }); volume.setValue(gs.getInt("music.volume")); properties.add(volume); properties.setPreferredSize(new Dimension(300, 125)); content.add(properties); JPanel browsePanel = new JPanel(); browsePanel.setBorder(BorderFactory.createTitledBorder("")); JButton browse = new JButton("Parcourir..."); if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) { preview.setEnabled(false); browse.setText(""); try { browse.setIcon(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png")))); } catch (IOException e) { e.printStackTrace(); } } browse.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JButton button = (JButton) event.getSource(); if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) { if (clip != null) { clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } name.setText(""); preview.setEnabled(false); button.setText("Parcourir..."); button.setIcon(null); new File("projects/" + Editor.getProjectName() + "/music.wav").delete(); gs.set("music.name", ""); } else { String path = null; JFileChooser chooser = new JFileChooser(Editor.lastPath); FileNameExtensionFilter filter = new FileNameExtensionFilter("Audio (WAV)", "wav"); chooser.setFileFilter(filter); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = chooser.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { path = chooser.getSelectedFile().getAbsolutePath(); Editor.lastPath = chooser.getSelectedFile().getParent(); copyMusic(new File(path)); button.setText(""); try { button.setIcon( new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png")))); } catch (IOException e) { e.printStackTrace(); } gs.set("music.name", new File(path).getName()); try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } name.setText(new File(path).getName()); preview.setEnabled(true); } } } }); if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) { preview.setEnabled(true); } else { preview.setEnabled(false); } preview.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JToggleButton tb = (JToggleButton) event.getSource(); if (tb.isSelected()) { try { audioStream = AudioSystem.getAudioInputStream( new File("projects/" + Editor.getProjectName() + "/music.wav")); format = audioStream.getFormat(); info = new DataLine.Info(Clip.class, format); clip = (Clip) AudioSystem.getLine(info); clip.open(audioStream); clip.start(); gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); gainControl.setValue(dB); if (loop.isSelected()) { clip.loop(Clip.LOOP_CONTINUOUSLY); } else { clip.loop(0); } clip.addLineListener(new LineListener() { @Override public void update(LineEvent event) { Clip clip = (Clip) event.getSource(); if (!clip.isRunning()) { preview.setSelected(false); clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }); } catch (Exception exc) { exc.printStackTrace(); } } else { clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }); JPanel buttons = new JPanel(); buttons.setLayout(new BorderLayout()); buttons.add(browse, BorderLayout.WEST); buttons.add(preview, BorderLayout.EAST); browsePanel.setLayout(new BorderLayout()); browsePanel.add(buttons, BorderLayout.NORTH); browsePanel.add(name, BorderLayout.SOUTH); name.setPreferredSize(new Dimension(280, 25)); name.setText(gs.getString("music.name")); content.add(browsePanel); this.setContentPane(content); this.setVisible(true); }
From source file:BasicPlayer.java
/** * Inits Audio ressources from InputStream. *///w ww .ja va 2 s . c om protected void initAudioInputStream(InputStream inputStream) throws UnsupportedAudioFileException, IOException { m_audioInputStream = AudioSystem.getAudioInputStream(inputStream); m_audioFileFormat = AudioSystem.getAudioFileFormat(inputStream); }
From source file:org.sipfoundry.voicemail.mailbox.AbstractMailboxManager.java
protected void concatAudio(File newFile, File orig1, File orig2) throws Exception { String operation = "dunno"; AudioInputStream clip1 = null; AudioInputStream clip2 = null; AudioInputStream concatStream = null; try {// w w w . jav a2 s. c o m operation = "getting AudioInputStream from " + orig1.getPath(); clip1 = AudioSystem.getAudioInputStream(orig1); operation = "getting AudioInputStream from " + orig2.getPath(); clip2 = AudioSystem.getAudioInputStream(orig2); operation = "building SequnceInputStream"; 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; throw new Exception(trouble, e); } finally { IOUtils.closeQuietly(clip1); IOUtils.closeQuietly(clip2); IOUtils.closeQuietly(concatStream); } }
From source file:SoundManagerTest.java
/** * Creates an AudioInputStream from a sound from an input stream *///from w ww. ja v a 2 s. c o m public AudioInputStream getAudioInputStream(InputStream is) { try { if (!is.markSupported()) { is = new BufferedInputStream(is); } // open the source stream AudioInputStream source = AudioSystem.getAudioInputStream(is); // convert to playback format return AudioSystem.getAudioInputStream(playbackFormat, source); } catch (UnsupportedAudioFileException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } return null; }
From source file:org.sipfoundry.voicemail.MessagesTest.java
public void testConcatAudio() throws Exception { File first = new File(m_testDir, "first.wav"); makeWaves(first, (byte) 0, 4); File second = new File(m_testDir, "second.wav"); makeWaves(second, (byte) -1, 4); File combined = new File(m_testDir, "combined.wav"); VmMessage.concatAudio(combined, first, second); assertTrue("combined.wav doesn't exist", combined.exists()); AudioInputStream ais = AudioSystem.getAudioInputStream(combined); byte[] octets = new byte[42]; int len = ais.read(octets); assertEquals(8, len);// ww w . ja v a 2 s . c om assertEquals(0, octets[0]); assertEquals(-1, octets[4]); }
From source file:com.limegroup.gnutella.gui.mp3.BasicPlayer.java
/** * Main loop.// ww w . j a va 2 s . co m * * Player Status == STOPPED => End of Thread + Freeing Audio Ressources.<br> * Player Status == PLAYING => Audio stream data sent to Audio line.<br> * Player Status == PAUSED => Waiting for another status. */ public void run() { LOG.debug("Thread Running"); //if (m_audioInputStream.markSupported()) m_audioInputStream.mark(m_audioFileFormat.getByteLength()); //else trace(1,getClass().getName(), "Mark not supported"); int nBytesRead = 1; m_status = PLAYING; int nBytesCursor = 0; byte[] abData = new byte[EXTERNAL_BUFFER_SIZE]; float nFrameSize = (float) m_line.getFormat().getFrameSize(); float nFrameRate = m_line.getFormat().getFrameRate(); float bytesPerSecond = nFrameSize * nFrameRate; int secondsTotal = Math.round((float) m_audioFileFormat.getByteLength() / bytesPerSecond); try { AudioMetaData amd = AudioMetaData.parseAudioFile(_file); if (amd != null) secondsTotal = amd.getLength(); } catch (IOException ignored) { } fireSeekSetupRequired(secondsTotal); try { while ((nBytesRead != -1) && (m_status != STOPPED)) { if (m_status == PLAYING) { try { if (doSeek > -1) { // Seek implementation. WAV format only ! if ((getAudioFileFormat() != null) && (getAudioFileFormat().getType().toString().startsWith("WAV"))) { if ((secondsTotal != AudioSystem.NOT_SPECIFIED) && (secondsTotal > 0)) { m_line.flush(); m_line.stop(); //m_audioInputStream.reset(); m_audioInputStream.close(); m_audioInputStream = AudioSystem.getAudioInputStream(_file); nBytesCursor = 0; if (m_audioFileFormat.getByteLength() - doSeek < abData.length) doSeek = m_audioFileFormat.getByteLength() - abData.length; doSeek = doSeek - doSeek % 4; int toSkip = (int) doSeek; // skip(...) instead of read(...) runs out of memory ?! while ((toSkip > 0) && (nBytesRead > 0)) { if (toSkip > abData.length) nBytesRead = m_audioInputStream.read(abData, 0, abData.length); else nBytesRead = m_audioInputStream.read(abData, 0, toSkip); toSkip = toSkip - nBytesRead; nBytesCursor = nBytesCursor + nBytesRead; } m_line.start(); } else { if (LOG.isDebugEnabled()) LOG.debug("Seek not supported for this InputStream : " + secondsTotal); } } else { if (LOG.isDebugEnabled()) LOG.debug("Seek not supported for this InputStream : " + secondsTotal); } doSeek = -1; } nBytesRead = m_audioInputStream.read(abData, 0, abData.length); } catch (Exception e) { if (LOG.isDebugEnabled()) LOG.debug("InputStream error : (" + nBytesRead + ")", e); e.printStackTrace(); m_status = STOPPED; } if (nBytesRead >= 0) { // make sure that you are writing an integral number of the // frame size (nFrameSize). i think this may skip a few // frames but probably not a big deal. if (nBytesRead % nFrameSize != 0) nBytesRead -= (nBytesRead % nFrameSize); int nBytesWritten = m_line.write(abData, 0, nBytesRead); nBytesCursor = nBytesCursor + nBytesWritten; m_framesRead = ((int) Math.round((float) nBytesCursor / bytesPerSecond)); } } else { try { Thread.sleep(1000); } catch (InterruptedException e) { LOG.debug("can't sleep", e); } } } } finally { // close the file and free the audio line. try { if (m_line != null) { try { m_line.drain(); m_line.stop(); } finally { try { m_line.close(); } catch (SecurityException ignored) { LOG.trace("Cannot Free Audio ressources", ignored); } m_line = null; } } } finally { if (m_audioInputStream != null) try { m_audioInputStream.close(); } catch (IOException ignored) { } } } LOG.trace("Thread Stopped"); firePlayComplete(); m_status = READY; }