Example usage for javax.sound.sampled AudioSystem isLineSupported

List of usage examples for javax.sound.sampled AudioSystem isLineSupported

Introduction

In this page you can find the example usage for javax.sound.sampled AudioSystem isLineSupported.

Prototype

public static boolean isLineSupported(Line.Info info) 

Source Link

Document

Indicates whether the system supports any lines that match the specified Line.Info object.

Usage

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 {/*www .  j  a  va 2  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:net.sf.firemox.tools.MToolKit.java

/**
 * loadClip loads the sound-file into a clip.
 * /*from  w  w w  .jav a2  s  .  co m*/
 * @param soundFile
 *          file to be loaded and played.
 */
public static void loadClip(String soundFile) {
    AudioFormat audioFormat = null;
    AudioInputStream actionIS = null;
    try {
        // actionIS = AudioSystem.getAudioInputStream(input); // Does not work !
        actionIS = AudioSystem.getAudioInputStream(MToolKit.getFile(MToolKit.getSoundFile(soundFile)));
        AudioFormat.Encoding targetEncoding = AudioFormat.Encoding.PCM_SIGNED;
        actionIS = AudioSystem.getAudioInputStream(targetEncoding, actionIS);
        audioFormat = actionIS.getFormat();

    } catch (UnsupportedAudioFileException afex) {
        Log.error(afex);
    } catch (IOException ioe) {

        if (ioe.getMessage().equalsIgnoreCase("mark/reset not supported")) { // Ignore
            Log.error("IOException ignored.");
        }
        Log.error(ioe.getStackTrace());
    }

    // define the required attributes for our line,
    // and make sure a compatible line is supported.

    // get the source data line for play back.
    DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
    if (!AudioSystem.isLineSupported(info)) {
        Log.error("LineCtrl matching " + info + " not supported.");
        return;
    }

    // Open the source data line for play back.
    try {
        Clip clip = null;
        try {
            Clip.Info info2 = new Clip.Info(Clip.class, audioFormat);
            clip = (Clip) AudioSystem.getLine(info2);
            clip.open(actionIS);
            clip.start();
        } catch (IOException ioe) {
            Log.error(ioe);
        }
    } catch (LineUnavailableException ex) {
        Log.error("Unable to open the line: " + ex);
        return;
    }
}

From source file:org.scantegrity.scanner.Scanner.java

private static void playAudioClip(int p_numTimes) {
    /*/* w  ww .  ja  v a  2 s  . c  o  m*/
     * Threaded Code....sigsegv when run
     * /
    if(c_audioThread != null && c_audioThread.isAlive()) {
       try {
    c_audioThread.join(2000);
       } catch (InterruptedException e) {
    c_log.log(Level.SEVERE, "Could not wait for previous sound thread.");
       }
    }
            
    c_audioThread = new Thread(new AudioFile(c_soundFile, p_numTimes));
    c_audioThread.start();
    /* 
     * End threaded Code
     */

    AudioInputStream l_stream = null;
    try {
        l_stream = AudioSystem.getAudioInputStream(new File(c_soundFileName));
    } catch (UnsupportedAudioFileException e_uaf) {
        c_log.log(Level.WARNING, "Unsupported Audio File");
        return;
    } catch (IOException e1) {
        c_log.log(Level.WARNING, "Could not Open Audio File");
        return;
    }

    AudioFormat l_format = l_stream.getFormat();
    Clip l_dataLine = null;
    DataLine.Info l_info = new DataLine.Info(Clip.class, l_format);

    if (!AudioSystem.isLineSupported(l_info)) {
        c_log.log(Level.WARNING, "Audio Line is not supported");
    }

    try {
        l_dataLine = (Clip) AudioSystem.getLine(l_info);
        l_dataLine.open(l_stream);
    } catch (LineUnavailableException ex) {
        c_log.log(Level.WARNING, "Audio Line is unavailable.");
    } catch (IOException e) {
        c_log.log(Level.WARNING, "Cannot playback Audio, IO Exception.");
    }

    l_dataLine.loop(p_numTimes);

    try {
        Thread.sleep(160 * (p_numTimes + 1));
    } catch (InterruptedException e) {
        c_log.log(Level.WARNING, "Could not sleep the audio player thread.");
    }

    l_dataLine.close();
}

From source file:org.snitko.app.record.SoundRecorder.java

public AudioInputStream record(long durationInSeconds) throws LineUnavailableException {
    Mixer.Info[] mixers = AudioSystem.getMixerInfo();
    for (Mixer.Info mixer : mixers) {
        System.out.printf("mixer name/desc/vendor/version: %s, %s, %s, %s\n", mixer.getName(),
                mixer.getDescription(), mixer.getVendor(), mixer.getVersion());
    }/* w  w  w . j  av a  2  s. c o m*/

    AudioFileFormat.Type[] types = AudioSystem.getAudioFileTypes();
    for (AudioFileFormat.Type type : types) {
        System.out.println("audio types are: " + type.toString());
    }

    AudioFormat audioFormat = getAudioFormat();

    // the targetDataLine from which audio data is captured
    TargetDataLine targetDataLine = AudioSystem.getTargetDataLine(audioFormat);
    System.out.println("targetDataLine: " + targetDataLine + "\n\tlineInfo" + targetDataLine.getLineInfo()
            + "\n\tformat: " + targetDataLine.getFormat());

    // checks if system supports the data targetDataLine
    if (!AudioSystem.isLineSupported(targetDataLine.getLineInfo())) {
        System.out.println("Line not supported");
        System.exit(0);
    }

    targetDataLine.addLineListener(new TimedLineListener(targetDataLine, durationInSeconds));
    targetDataLine.open(audioFormat);
    targetDataLine.start(); // start capturing

    System.out.println("Start capturing...");
    AudioInputStream audioInputStream = new AudioInputStream(targetDataLine);
    System.out.println("Start recording...");
    return audioInputStream;
}

From source file:tvbrowser.extras.reminderplugin.ReminderPlugin.java

/**
 * Plays a sound.//from ww  w  . ja  va  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;
}