Example usage for javax.sound.sampled AudioInputStream read

List of usage examples for javax.sound.sampled AudioInputStream read

Introduction

In this page you can find the example usage for javax.sound.sampled AudioInputStream read.

Prototype

@Override
public int read(byte[] b) throws IOException 

Source Link

Document

Reads some number of bytes from the audio input stream and stores them into the buffer array b .

Usage

From source file:edu.mit.csail.sls.wami.portal.xmlrpc.XmlRpcPortalRecognizer.java

private void pretendToRecognize(AudioInputStream audioIn) throws IOException {
    int chunkSize = 1024 * 10;
    byte[] buffer = new byte[chunkSize];

    while (true) {
        int nRead = audioIn.read(buffer);
        System.out.println("Read Bytes:" + nRead);

        if (nRead <= 0) {
            break;
        }/*from   ww w . j a v  a  2 s .c om*/
    }
}

From source file:fr.ritaly.dungeonmaster.audio.SoundSystemV1.java

public synchronized void init(final File directory)
        throws IOException, UnsupportedAudioFileException, LineUnavailableException {

    Validate.isTrue(directory != null, "The given directory is null");
    Validate.isTrue(directory.exists(),/*  w  w w .  j  a v a 2s  .c o m*/
            "The given directory <" + directory.getAbsolutePath() + "> doesn't exist");
    Validate.isTrue(directory.isDirectory(),
            "The given path <" + directory.getAbsolutePath() + "> doesn't denote a directory");

    if (initialized) {
        throw new IllegalStateException("The sound system is already initialized");
    }

    if (log.isDebugEnabled()) {
        log.debug("Initializing sound system ...");
    }

    // Lister les fichiers du rpertoire
    File[] files = directory.listFiles();

    for (File file : files) {
        final AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);

        final AudioFormat format = audioInputStream.getFormat();

        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream((int) file.length());

        final byte[] buffer = new byte[4096];

        int count = -1;

        while ((count = audioInputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, count);
        }

        final Sound sound = new Sound(outputStream.toByteArray(), format);

        sounds.put(file.getName(), sound);
    }

    this.executorService = Executors.newFixedThreadPool(4);

    if (log.isInfoEnabled()) {
        log.info("Sound system initialized");
    }

    initialized = true;
}

From source file:fr.ritaly.dungeonmaster.audio.SoundSystem.java

public synchronized void init(final File directory)
        throws IOException, UnsupportedAudioFileException, LineUnavailableException {

    Validate.isTrue(directory != null, "The given directory is null");
    Validate.isTrue(directory.exists(),// www .j av  a  2 s .  c  om
            "The given directory <" + directory.getAbsolutePath() + "> doesn't exist");
    Validate.isTrue(directory.isDirectory(),
            "The given path <" + directory.getAbsolutePath() + "> doesn't denote a directory");

    if (initialized) {
        throw new IllegalStateException("The sound system is already initialized");
    }

    if (log.isDebugEnabled()) {
        log.debug("Initializing sound system ...");
    }

    // Lister les fichiers du rpertoire
    File[] files = directory.listFiles();

    for (File file : files) {
        final AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);

        final AudioFormat format = audioInputStream.getFormat();

        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream((int) file.length());

        final byte[] buffer = new byte[4096];

        int count = -1;

        while ((count = audioInputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, count);
        }

        final Sound sound = new Sound(outputStream.toByteArray(), format);

        sounds.put(file.getName(), sound);
    }

    // On peut jouer au maximum 4 sons en mme temps
    this.executorService = Executors.newFixedThreadPool(4);

    if (log.isInfoEnabled()) {
        log.info("Sound system initialized");
    }

    initialized = true;
}

From source file:edu.mit.csail.sls.wami.portal.xmlrpc.XmlRpcPortalRecognizer.java

private List<String> getRecognitionResults(AudioInputStream audioIn, ArrayList<Future<?>> futures,
        final IRecognitionListener listener) throws XmlRpcException, IOException {
    int chunkSize = 1024 * 10;
    // int chunkSize = 2 << 10; // kB
    byte[] buffer = new byte[chunkSize];
    byte[] sendBuffer = new byte[chunkSize];
    String lastPartial = null;//from  w ww  . ja  va 2  s  . c o  m

    Object[] sessionIdParams = { sessionId };
    int totalSent = 0;
    while (true) {
        int nRead = audioIn.read(buffer);
        System.out.println("Read Bytes:" + nRead);

        if (nRead <= 0) {
            break;
        }

        if (nRead > 0) {
            // reuse buffer when possible
            byte[] toSend = (nRead == chunkSize) ? sendBuffer : new byte[nRead];
            System.arraycopy(buffer, 0, toSend, 0, nRead);
            Object[] writeParams = { sessionId, toSend };
            totalSent += nRead;

            if (incrementalResults) {
                final String partial = (String) client.execute("Portal.writePartial", writeParams);

                if (!partial.equals(lastPartial)) {
                    // System.out.println("partial: " + partial);
                    futures.add(recognizeCallbackExecutor.submit(new Runnable() {
                        public void run() {
                            List<String> hyps = Collections.singletonList(partial);
                            final IRecognitionResult result = new RecognitionResult(true, hyps);
                            listener.onRecognitionResult(result);
                        }
                    }));
                    // listener.result(result, isIncremental)
                    lastPartial = partial;
                }
            } else {
                client.execute("Portal.write", writeParams);
            }
        }
    }

    Object[] nbest = (Object[]) client.execute("Portal.closeUtterance", sessionIdParams);
    ArrayList<String> hyps = new ArrayList<String>(nbest.length);
    for (Object o : nbest) {
        Map<String, String> map = (Map<String, String>) o;
        hyps.add(map.get("text"));
    }

    // System.out.println("hyps:");
    // System.out.println(hyps);

    return hyps;
}

From source file:com.gameminers.mav.firstrun.TeachSphinxThread.java

@Override
public void run() {
    try {/*from w  w w .  j a va2s. co m*/
        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: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);/*from  ww w .j a  va2  s  .  co m*/
    assertEquals(0, octets[0]);
    assertEquals(-1, octets[4]);
}

From source file:sec_algo.aud_sec.java

public BufferedWriter getAudioStream() {
    FileInputStream fin = null;/*from   ww  w  .j av a  2s . c  o m*/
    BufferedWriter audstream = null;

    try {
        fin = new FileInputStream(this.file);
        //           audstream = new BufferedWriter(new FileWriter(returnFileName()+"_ex."+returnFileExt()));
        //           byte contents[] = new byte[100];
        //           while(fin.read(contents)!= -1){
        //               System.out.println("reading & writing from file");
        //               for(byte b : contents)
        //                   for(int x = 0; x < 8; x++)
        //                       audstream.write(b>>x & 1);
        //           }
        //           System.out.println("Finished!");
        //           System.out.println("audstream contents: " + audstream.toString());
        byte[] header = new byte[8];
        fin.read(header);
        fin.close();
        //           System.out.println("header bytes: " + Arrays.toString(header));
        ArrayList<String> bitstring = new ArrayList<String>();
        for (int i = 0; i < header.length; i++)
            bitstring.add(String.format("%8s", Integer.toBinaryString(header[i] & 0xFF)).replace(' ', '0'));
        System.out.print("bit input: [/");
        for (int i = 0; i < bitstring.size(); i++) {
            System.out.print(bitstring.get(i) + " ");
        }
        System.out.println("]/");

        System.out.println(bitstring.get(0) + " " + bitstring.get(1) + " " + bitstring.get(2));
        System.out.println("Bitrate index: " + bitstring.get(2).substring(0, 4));

        AudioInputStream in = AudioSystem.getAudioInputStream(this.file);
        AudioInputStream din = null;
        AudioFormat baseFormat = in.getFormat();
        AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(),
                getBitrate(bitstring.get(2).substring(0, 4)), baseFormat.getChannels(),
                baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
        din = AudioSystem.getAudioInputStream(decodedFormat, in);
        int size = din.available();
        byte[] bytaud = new byte[size];
        din.read(bytaud);
        bitstring = new ArrayList<String>();
        for (int i = 0; i < header.length; i++)
            bitstring.add(String.format("%8s", Integer.toBinaryString(header[i] & 0xFF)).replace(' ', '0'));
        System.out.print("bit input: [/");
        for (int i = 0; i < bitstring.size(); i++) {
            System.out.print(bitstring.get(i) + " ");
        }
        System.out.println("]/");
        in.close();
        din.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return audstream;
}