Ejemplo n.º 1
0
 /**
  * Stop recording and give us the clip.
  *
  * @return the clip that was recorded since the last time start was called
  * @see #start
  */
 public short[] stop() {
   synchronized (lock) {
     if (recorder == null) {
       return new short[0];
     }
     ByteArrayOutputStream out = recorder.stopRecording();
     microphone.close();
     recorder = null;
     byte audioBytes[] = out.toByteArray();
     ByteArrayInputStream in = new ByteArrayInputStream(audioBytes);
     try {
       short[] samples = RawReader.readAudioData(in, inFormat);
       if (downsample) {
         samples =
             Downsampler.downsample(
                 samples,
                 (int) (inFormat.getSampleRate() / 1000.0f),
                 (int) (outFormat.getSampleRate() / 1000.0f));
       }
       return samples;
     } catch (IOException e) {
       e.printStackTrace();
       return new short[0];
     }
   }
 }
Ejemplo n.º 2
0
 /** @see com.groovemanager.sampled.AudioPlayerProvider#rec(byte[], int, int) */
 public int rec(byte[] b, int offset, int length) {
   if (this.editor.player.getStatus() != AudioPlayer.RECORDING
       && this.editor.player.getStatus() != AudioPlayer.PAUSE_REC) return 0;
   int written = 0;
   try {
     out.write(b, offset, length);
     written = length;
     ((DynamicAudioFileWaveForm) afWF).append(b, offset, length);
     afSource.appendFrames(length / format.getFrameSize());
   } catch (IOException e) {
     e.printStackTrace();
   }
   recCount += written / format.getFrameSize();
   if (recCount >= format.getSampleRate()) {
     recCount -= format.getSampleRate();
     waveDisplay
         .getComposite()
         .getDisplay()
         .asyncExec(
             new Runnable() {
               public void run() {
                 waveDisplay.zoom(getTotalLength() / 30.0 / format.getSampleRate());
                 cutList.update();
               }
             });
   }
   return written;
 }
Ejemplo n.º 3
0
 public AudioRecordingStream getAudioRecordingStream(String filename, int bufferSize) {
   AudioRecordingStream mstream = null;
   if (getAudioInputStream(filename) == null)
     debug("Reading from " + getAudioInputStream(filename).getClass().toString());
   if (getAudioInputStream(filename) != null) {
     debug("File format is: " + getAudioInputStream(filename).getFormat().toString());
     AudioFormat format = getAudioInputStream(filename).getFormat();
     // special handling for mp3 files because
     // they need to be converted to PCM
     if (format instanceof MpegAudioFormat) {
       AudioFormat baseFormat = format;
       format =
           new AudioFormat(
               AudioFormat.Encoding.PCM_SIGNED,
               baseFormat.getSampleRate(),
               16,
               baseFormat.getChannels(),
               baseFormat.getChannels() * 2,
               baseFormat.getSampleRate(),
               false);
       // converts the stream to PCM audio from mp3 audio
       AudioInputStream decAis = getAudioInputStream(format, getAudioInputStream(filename));
       // source data line is for sending the file audio out to the
       // speakers
       SourceDataLine line = getSourceDataLine(format, bufferSize);
       if (decAis != null && line != null) {
         Map<String, Object> props = getID3Tags(filename);
         long lengthInMillis = -1;
         if (props.containsKey("duration")) {
           Long dur = (Long) props.get("duration");
           if (dur.longValue() > 0) {
             lengthInMillis = dur.longValue() / 1000;
           }
         }
         MP3MetaData meta = new MP3MetaData(filename, lengthInMillis, props);
         mstream =
             new JSMPEGAudioRecordingStream(
                 this, meta, getAudioInputStream(filename), decAis, line, bufferSize);
       }
     } // format instanceof MpegAudioFormat
     else {
       // source data line is for sending the file audio out to the
       // speakers
       SourceDataLine line = getSourceDataLine(format, bufferSize);
       if (line != null) {
         long length =
             AudioUtils.frames2Millis(getAudioInputStream(filename).getFrameLength(), format);
         BasicMetaData meta = new BasicMetaData(filename, length);
         mstream =
             new JSPCMAudioRecordingStream(
                 this, meta, getAudioInputStream(filename), line, bufferSize);
       }
     } // else
   } // ais != null
   return mstream;
 }
Ejemplo n.º 4
0
  // http://stackoverflow.com/questions/13789063/get-sound-from-a-url-with-java
  private void playMP3(final String url) {

    try {

      // Create the JavaFX Panel for the WebView
      JFXPanel fxPanel = new JFXPanel();
      fxPanel.setLocation(new Point(0, 0));

      // Initialize the webView in a JavaFX-Thread
      Platform.runLater(
          new Runnable() {
            public void run() {
              MediaPlayer player = new MediaPlayer(new Media(url));
              player.play();
            }
          });

      if (true) return;

      AudioInputStream in = AudioSystem.getAudioInputStream(new URL(url));
      AudioFormat baseFormat = in.getFormat();
      AudioFormat decodedFormat =
          new AudioFormat(
              AudioFormat.Encoding.PCM_SIGNED,
              baseFormat.getSampleRate(),
              16,
              baseFormat.getChannels(),
              baseFormat.getChannels() * 2,
              baseFormat.getSampleRate(),
              false);
      AudioInputStream din = AudioSystem.getAudioInputStream(decodedFormat, in);
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
      SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
      if (line != null) {
        line.open(decodedFormat);
        byte[] data = new byte[4096];
        // Start
        line.start();

        int nBytesRead;
        while ((nBytesRead = din.read(data, 0, data.length)) != -1) {
          line.write(data, 0, nBytesRead);
        }
        // Stop
        line.drain();
        line.stop();
        line.close();
        din.close();
      }
    } catch (Exception e) {
      App.debug("playing MP3 failed " + url + " " + e.toString());
    }
  }
Ejemplo n.º 5
0
 public AudioSample getAudioSample(String filename, int bufferSize) {
   AudioInputStream ais = getAudioInputStream(filename);
   if (ais != null) {
     AudioMetaData meta = null;
     AudioFormat format = ais.getFormat();
     FloatSampleBuffer samples = null;
     if (format instanceof MpegAudioFormat) {
       AudioFormat baseFormat = format;
       format =
           new AudioFormat(
               AudioFormat.Encoding.PCM_SIGNED,
               baseFormat.getSampleRate(),
               16,
               baseFormat.getChannels(),
               baseFormat.getChannels() * 2,
               baseFormat.getSampleRate(),
               false);
       // converts the stream to PCM audio from mp3 audio
       ais = getAudioInputStream(format, ais);
       // get a map of properties so we can find out how long it is
       Map<String, Object> props = getID3Tags(filename);
       // there is a property called mp3.length.bytes, but that is
       // the length in bytes of the mp3 file, which will of course
       // be much shorter than the decoded version. so we use the
       // duration of the file to figure out how many bytes the
       // decoded file will be.
       long dur = ((Long) props.get("duration")).longValue();
       int toRead = (int) AudioUtils.millis2Bytes(dur / 1000, format);
       samples = loadFloatAudio(ais, toRead);
       meta = new MP3MetaData(filename, dur / 1000, props);
     } else {
       samples = loadFloatAudio(ais, (int) ais.getFrameLength() * format.getFrameSize());
       long length = AudioUtils.frames2Millis(samples.getSampleCount(), format);
       meta = new BasicMetaData(filename, length);
     }
     AudioSynthesizer out =
         getAudioSynthesizer(
             format.getChannels(),
             bufferSize,
             format.getSampleRate(),
             format.getSampleSizeInBits());
     if (out != null) {
       SampleSignal ssig = new SampleSignal(samples);
       out.setAudioSignal(ssig);
       return new JSAudioSample(meta, ssig, out);
     } else {
       error("Couldn't acquire an output.");
     }
   }
   return null;
 }
Ejemplo n.º 6
0
 /**
  * Inits a DateLine.<br>
  * We check if the line supports Gain and Pan controls.
  *
  * <p>From the AudioInputStream, i.e. from the sound file, we fetch information about the format
  * of the audio data. These information include the sampling frequency, the number of channels and
  * the size of the samples. There information are needed to ask JavaSound for a suitable output
  * line for this audio file. Furthermore, we have to give JavaSound a hint about how big the
  * internal buffer for the line should be. Here, we say AudioSystem.NOT_SPECIFIED, signaling that
  * we don't care about the exact size. JavaSound will use some default value for the buffer size.
  */
 protected void createLine() throws LineUnavailableException {
   log.info("Create Line");
   if (m_line == null) {
     AudioFormat sourceFormat = m_audioInputStream.getFormat();
     log.info("Create Line : Source format : " + sourceFormat.toString());
     int nSampleSizeInBits = sourceFormat.getSampleSizeInBits();
     if (nSampleSizeInBits <= 0) {
       nSampleSizeInBits = 16;
     }
     if ((sourceFormat.getEncoding() == AudioFormat.Encoding.ULAW)
         || (sourceFormat.getEncoding() == AudioFormat.Encoding.ALAW)) {
       nSampleSizeInBits = 16;
     }
     if (nSampleSizeInBits != 8) {
       nSampleSizeInBits = 16;
     }
     AudioFormat targetFormat =
         new AudioFormat(
             AudioFormat.Encoding.PCM_SIGNED,
             sourceFormat.getSampleRate(),
             nSampleSizeInBits,
             sourceFormat.getChannels(),
             sourceFormat.getChannels() * (nSampleSizeInBits / 8),
             sourceFormat.getSampleRate(),
             false);
     log.info("Create Line : Target format: " + targetFormat);
     // Keep a reference on encoded stream to progress notification.
     m_encodedaudioInputStream = m_audioInputStream;
     try {
       // Get total length in bytes of the encoded stream.
       encodedLength = m_encodedaudioInputStream.available();
     } catch (IOException e) {
       log.log(Level.SEVERE, "Cannot get m_encodedaudioInputStream.available()", e);
     }
     // Create decoded stream.
     m_audioInputStream = AudioSystem.getAudioInputStream(targetFormat, m_audioInputStream);
     AudioFormat audioFormat = m_audioInputStream.getFormat();
     DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat, -1);
     Mixer mixer = getMixer(m_mixerName);
     if (mixer != null) {
       log.info("Mixer : " + mixer.getMixerInfo().toString());
       m_line = (SourceDataLine) mixer.getLine(info);
     } else {
       m_line = (SourceDataLine) AudioSystem.getLine(info);
       m_mixerName = null;
     }
     log.info("Line : " + m_line.toString());
     log.info("Line Info : " + m_line.getLineInfo().toString());
     log.info("Line AudioFormat: " + m_line.getFormat().toString());
   }
 }
Ejemplo n.º 7
0
  public AudioInputStream getAudioInputStream(
      AudioFormat.Encoding targetEncoding, AudioInputStream sourceStream) {
    AudioFormat sourceFormat = sourceStream.getFormat();
    AudioFormat.Encoding sourceEncoding = sourceFormat.getEncoding();

    if (sourceEncoding.equals(targetEncoding)) {
      return sourceStream;
    } else {
      AudioFormat targetFormat = null;
      if (!isConversionSupported(targetEncoding, sourceStream.getFormat())) {
        throw new IllegalArgumentException(
            "Unsupported conversion: "
                + sourceStream.getFormat().toString()
                + " to "
                + targetEncoding.toString());
      }
      if (AudioFormat.Encoding.ULAW.equals(sourceEncoding)
          && AudioFormat.Encoding.PCM_SIGNED.equals(targetEncoding)) {
        targetFormat =
            new AudioFormat(
                targetEncoding,
                sourceFormat.getSampleRate(),
                16,
                sourceFormat.getChannels(),
                2 * sourceFormat.getChannels(),
                sourceFormat.getSampleRate(),
                sourceFormat.isBigEndian());
      } else if (AudioFormat.Encoding.PCM_SIGNED.equals(sourceEncoding)
          && AudioFormat.Encoding.ULAW.equals(targetEncoding)) {
        targetFormat =
            new AudioFormat(
                targetEncoding,
                sourceFormat.getSampleRate(),
                8,
                sourceFormat.getChannels(),
                sourceFormat.getChannels(),
                sourceFormat.getSampleRate(),
                false);
      } else {
        throw new IllegalArgumentException(
            "Unsupported conversion: "
                + sourceStream.getFormat().toString()
                + " to "
                + targetEncoding.toString());
      }

      return getAudioInputStream(targetFormat, sourceStream);
    }
  }
Ejemplo n.º 8
0
 /**
  * Numbers used here are verbatim from Javazoom
  *
  * @param baseFormat
  * @return
  */
 private AudioFormat getDecodedFormat(AudioFormat baseFormat) {
   // Do we need to "decode" the base format?
   if (AudioFormat.Encoding.PCM_SIGNED.equals(baseFormat.getEncoding())
       || AudioFormat.Encoding.PCM_UNSIGNED.equals(baseFormat.getEncoding())) {
     return baseFormat;
   }
   return new AudioFormat(
       AudioFormat.Encoding.PCM_SIGNED,
       baseFormat.getSampleRate(),
       16,
       baseFormat.getChannels(),
       baseFormat.getChannels() * 2,
       baseFormat.getSampleRate(),
       false);
 }
Ejemplo n.º 9
0
 public AudioRecording getAudioRecordingClip(String filename) {
   Clip clip = null;
   AudioMetaData meta = null;
   AudioInputStream ais = getAudioInputStream(filename);
   if (ais != null) {
     AudioFormat format = ais.getFormat();
     if (format instanceof MpegAudioFormat) {
       AudioFormat baseFormat = format;
       format =
           new AudioFormat(
               AudioFormat.Encoding.PCM_SIGNED,
               baseFormat.getSampleRate(),
               16,
               baseFormat.getChannels(),
               baseFormat.getChannels() * 2,
               baseFormat.getSampleRate(),
               false);
       // converts the stream to PCM audio from mp3 audio
       ais = getAudioInputStream(format, ais);
     }
     DataLine.Info info = new DataLine.Info(Clip.class, ais.getFormat());
     if (AudioSystem.isLineSupported(info)) {
       // Obtain and open the line.
       try {
         clip = (Clip) AudioSystem.getLine(info);
         clip.open(ais);
       } catch (Exception e) {
         error("Error obtaining Javasound Clip: " + e.getMessage());
         return null;
       }
       Map<String, Object> props = getID3Tags(filename);
       long lengthInMillis = -1;
       if (props.containsKey("duration")) {
         Long dur = (Long) props.get("duration");
         lengthInMillis = dur.longValue() / 1000;
       }
       meta = new MP3MetaData(filename, lengthInMillis, props);
     } else {
       error("File format not supported.");
       return null;
     }
   }
   if (meta == null) {
     // this means we're dealing with not-an-mp3
     meta = new BasicMetaData(filename, clip.getMicrosecondLength() / 1000);
   }
   return new JSAudioRecordingClip(clip, meta);
 }
Ejemplo n.º 10
0
 public AudioSample getAudioSample(
     float[] left, float[] right, AudioFormat format, int bufferSize) {
   FloatSampleBuffer sample = new FloatSampleBuffer(2, left.length, format.getSampleRate());
   System.arraycopy(left, 0, sample.getChannel(0), 0, left.length);
   System.arraycopy(right, 0, sample.getChannel(1), 0, right.length);
   return getAudioSampleImp(sample, format, bufferSize);
 }
Ejemplo n.º 11
0
    protected void startFile(File file) {
      currentFile = file;
      AudioFormat format;
      try {
        format = AudioSystem.getAudioFileFormat(file).getFormat();
        float samplerate = format.getSampleRate();
        int size = 1024;
        int overlap = 0;

        PitchResyntheziser prs = new PitchResyntheziser(samplerate);
        estimationGain = new GainProcessor(estimationGainSlider.getValue() / 100.0);
        estimationDispatcher = AudioDispatcher.fromFile(file, size, overlap);
        estimationDispatcher.addAudioProcessor(new PitchProcessor(algo, samplerate, size, prs));
        estimationDispatcher.addAudioProcessor(estimationGain);
        estimationDispatcher.addAudioProcessor(new AudioPlayer(format));

        sourceGain = new GainProcessor(sourceGainSlider.getValue() / 100.0);
        sourceDispatcher = AudioDispatcher.fromFile(file, size, overlap);
        sourceDispatcher.addAudioProcessor(sourceGain);
        sourceDispatcher.addAudioProcessor(new AudioPlayer(format));

        new Thread(estimationDispatcher).start();
        new Thread(sourceDispatcher).start();

      } catch (UnsupportedAudioFileException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (LineUnavailableException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
Ejemplo n.º 12
0
  /**
   * Sets the InputStream from which this StreamDataSource reads.
   *
   * @param inputStream the InputStream from which audio data comes
   * @param streamName the name of the InputStream
   */
  public void setInputStream(AudioInputStream inputStream, String streamName) {
    dataStream = inputStream;
    streamEndReached = false;
    utteranceEndSent = false;
    utteranceStarted = false;

    AudioFormat format = inputStream.getFormat();
    sampleRate = (int) format.getSampleRate();
    bigEndian = format.isBigEndian();

    String s = format.toString();
    logger.finer("input format is " + s);

    if (format.getSampleSizeInBits() % 8 != 0)
      throw new Error("StreamDataSource: bits per sample must be a multiple of 8.");
    bytesPerValue = format.getSampleSizeInBits() / 8;

    // test whether all files in the stream have the same format

    AudioFormat.Encoding encoding = format.getEncoding();
    if (encoding.equals(AudioFormat.Encoding.PCM_SIGNED)) signedData = true;
    else if (encoding.equals(AudioFormat.Encoding.PCM_UNSIGNED)) signedData = false;
    else throw new RuntimeException("used file encoding is not supported");

    totalValuesRead = 0;
  }
Ejemplo n.º 13
0
  private void loadFile(String basename) {
    try {
      File wavFile = new File(wavDir, basename + db.getProp(db.WAVEXT));
      if (!wavFile.exists())
        throw new IllegalArgumentException("File " + wavFile.getAbsolutePath() + " does not exist");
      File labFile = new File(phoneLabDir, basename + db.getProp(db.LABEXT));
      if (!labFile.exists())
        throw new IllegalArgumentException("File " + labFile.getAbsolutePath() + " does not exist");
      // pm file is optional
      File pmFile = new File(pmDir, basename + db.getProp(PMEXT));
      if (pmFile.exists()) {
        System.out.println("Loading pitchmarks file " + pmFile.getAbsolutePath());
        pitchmarks = new ESTTextfileDoubleDataSource(pmFile).getAllData();
      } else {
        System.out.println("Pitchmarks file " + pmFile.getAbsolutePath() + " does not exist");
        pitchmarks = null;
      }

      AudioInputStream ais = AudioSystem.getAudioInputStream(wavFile);
      audioFormat = ais.getFormat();
      samplingRate = (int) audioFormat.getSampleRate();
      audioSignal = new AudioDoubleDataSource(ais).getAllData();

      String file = FileUtils.getFileAsString(labFile, "ASCII");
      String[] lines = file.split("\n");
      labels.setListData(lines);

      saveFilename.setText(basename);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 14
0
 public void play(InputStream source) {
   int bufferSize = format.getFrameSize() * Math.round(format.getSampleRate() / 10);
   byte[] buffer = new byte[bufferSize];
   SourceDataLine line;
   try {
     DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
     line = (SourceDataLine) AudioSystem.getLine(info);
     line.open(format, bufferSize);
   } catch (LineUnavailableException e) {
     e.printStackTrace();
     return;
   }
   line.start();
   try {
     int numBytesRead = 0;
     while (numBytesRead != -1) {
       numBytesRead = source.read(buffer, 0, buffer.length);
       if (numBytesRead != -1) line.write(buffer, 0, numBytesRead);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   line.drain();
   line.close();
 }
Ejemplo n.º 15
0
  /** Signals that a PooledThread has started. Creates the Thread's line and buffer. */
  protected void threadStarted() {
    // wait for the SoundManager constructor to finish
    synchronized (this) {
      try {
        wait();
      } catch (InterruptedException ex) {
      }
    }

    // use a short, 100ms (1/10th sec) buffer for filters that
    // change in real-time
    int bufferSize =
        playbackFormat.getFrameSize() * Math.round(playbackFormat.getSampleRate() / 10);

    // create, open, and start the line
    SourceDataLine line;
    DataLine.Info lineInfo = new DataLine.Info(SourceDataLine.class, playbackFormat);
    try {
      line = (SourceDataLine) AudioSystem.getLine(lineInfo);
      line.open(playbackFormat, bufferSize);
    } catch (LineUnavailableException ex) {
      // the line is unavailable - signal to end this thread
      Thread.currentThread().interrupt();
      return;
    }

    line.start();

    // create the buffer
    byte[] buffer = new byte[bufferSize];

    // set this thread's locals
    localLine.set(line);
    localBuffer.set(buffer);
  }
Ejemplo n.º 16
0
 /**
  * Test method for {@link net.sourceforge.gjtapi.protocols.JavaSoundParser#parse(java.net.URL)} .
  *
  * @exception Exception test failed.
  */
 @Test
 public void testParse() throws Exception {
   final URL url = new URL("playback://audio?rate=8000&channels=2&encoding=pcm");
   AudioFormat format = JavaSoundParser.parse(url);
   Assert.assertEquals(new Float(8000.0), new Float(format.getSampleRate()));
   Assert.assertEquals(2, format.getChannels());
   Assert.assertEquals(AudioFormat.Encoding.PCM_SIGNED, format.getEncoding());
 }
Ejemplo n.º 17
0
 private static boolean checkConversion(
     AudioFormat srcFormat, AudioFormat.Encoding targetEncoding, boolean neg) {
   AudioInputStream srcStream =
       new AudioInputStream(new ByteArrayInputStream(new byte[0]), srcFormat, -1);
   boolean couldConvert = true;
   try {
     AudioInputStream targetStream = AudioSystem.getAudioInputStream(targetEncoding, srcStream);
     // always a failure if src bits != target bits, or src channels !=
     // target channels
     AudioFormat targetFormat = targetStream.getFormat();
     if (!isSameBitsChannelSampleRate(srcFormat, targetFormat)) {
       System.out.println("ERROR");
       System.out.println(
           "  converted stream has "
               + targetFormat.getChannels()
               + " channels, "
               + targetFormat.getSampleSizeInBits()
               + " bits, and "
               + targetFormat.getSampleRate()
               + "Hz, "
               + " but source stream had "
               + srcFormat.getChannels()
               + " channels, "
               + srcFormat.getSampleSizeInBits()
               + " bits, and "
               + srcFormat.getSampleRate()
               + "Hz");
       return false;
     }
   } catch (Exception e) {
     couldConvert = false;
   }
   if (couldConvert == neg) {
     System.out.println("ERROR");
     System.out.println(
         "  can"
             + ((!couldConvert) ? "not" : "")
             + " convert from "
             + srcFormat
             + " to "
             + targetEncoding);
     return false;
   }
   System.out.println("OK");
   return true;
 }
 /**
  * Store an AudioFormat
  *
  * @param audioFormat
  */
 public AudioFormatTransport(AudioFormat audioFormat) {
   _channels = audioFormat.getChannels();
   _encoding = audioFormat.getEncoding().toString();
   _frameRate = audioFormat.getFrameRate();
   _frameSize = audioFormat.getFrameSize();
   _sampleRate = audioFormat.getSampleRate();
   _sampleSizeInBits = audioFormat.getSampleSizeInBits();
   _isBigEndian = audioFormat.isBigEndian();
   _properties = audioFormat.properties();
 }
Ejemplo n.º 19
0
 private static boolean checkDirect(AudioFormat srcFormat, boolean neg) {
   AudioFormat targetFormat =
       new AudioFormat(
           srcFormat.getSampleRate(),
           srcFormat.getSampleSizeInBits(),
           srcFormat.getChannels(),
           true,
           false);
   return checkConversion(srcFormat, targetFormat, neg);
 }
Ejemplo n.º 20
0
  public static Clip loadClip(URL url) {
    Clip clip = null;
    String fnm = "" + url;
    try {
      AudioInputStream stream = AudioSystem.getAudioInputStream(url);
      AudioFormat format = stream.getFormat();

      if ((format.getEncoding() == AudioFormat.Encoding.ULAW)
          || (format.getEncoding() == AudioFormat.Encoding.ALAW)) {
        AudioFormat newFormat =
            new AudioFormat(
                AudioFormat.Encoding.PCM_SIGNED,
                format.getSampleRate(),
                format.getSampleSizeInBits() * 2,
                format.getChannels(),
                format.getFrameSize() * 2,
                format.getFrameRate(),
                true); // big endian
        stream = AudioSystem.getAudioInputStream(newFormat, stream);
        // System.out.println("Converted Audio format: " + newFormat);
        format = newFormat;
      }

      DataLine.Info info = new DataLine.Info(Clip.class, format);

      // make sure sound system supports data line
      if (!AudioSystem.isLineSupported(info)) {
        System.out.println("Unsupported Clip File: " + fnm);
        return null;
      }
      // get clip line resource
      clip = (Clip) AudioSystem.getLine(info);
      clip.open(stream); // open the sound file as a clip
      stream.close(); // we're done with the input stream
      // duration (in secs) of the clip
      double duration = clip.getMicrosecondLength() / 1000000.0; // new
      if (duration <= 1.0) {
        System.out.println("WARNING. Duration <= 1 sec : " + duration + " secs");
        System.out.println(
            "         The clip in " + fnm + " may not play in J2SE 1.5 -- make it longer");
      }
      // else
      //  System.out.println(fnm + ": Duration: " + duration + " secs");
    } // end of try block
    catch (UnsupportedAudioFileException audioException) {
      System.out.println("Unsupported audio file: " + fnm);
    } catch (LineUnavailableException noLineException) {
      System.out.println("No audio line available for : " + fnm);
    } catch (IOException ioException) {
      System.out.println("Could not read: " + fnm);
    } catch (Exception e) {
      System.out.println("Problem with " + fnm);
    }
    return clip;
  } // end of loadClip()
Ejemplo n.º 21
0
  public void open(AudioInputStream stream) throws IOException, LineUnavailableException {

    AudioInputStream is1;
    format = stream.getFormat();

    if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
      is1 = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, stream);
    } else {
      is1 = stream;
    }
    format = is1.getFormat();
    InputStream is2;
    if (parent != null) {
      ProgressMonitorInputStream pmis =
          new ProgressMonitorInputStream(parent, "Loading track..", is1);
      pmis.getProgressMonitor().setMillisToPopup(0);
      is2 = pmis;
    } else {
      is2 = is1;
    }

    byte[] buf = new byte[2 ^ 16];
    int totalRead = 0;
    int numRead = 0;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    numRead = is2.read(buf);
    while (numRead > -1) {
      baos.write(buf, 0, numRead);
      numRead = is2.read(buf, 0, buf.length);
      totalRead += numRead;
    }
    is2.close();
    audioData = baos.toByteArray();
    AudioFormat afTemp;
    if (format.getChannels() < 2) {
      afTemp =
          new AudioFormat(
              format.getEncoding(),
              format.getSampleRate(),
              format.getSampleSizeInBits(),
              2,
              format.getSampleSizeInBits() * 2 / 8, // calculate
              // frame
              // size
              format.getFrameRate(),
              format.isBigEndian());
    } else {
      afTemp = format;
    }

    setLoopPoints(0, audioData.length);
    dataLine = AudioSystem.getSourceDataLine(afTemp);
    dataLine.open();
    inputStream = new ByteArrayInputStream(audioData);
  }
Ejemplo n.º 22
0
 public AudioRecording getAudioRecording(String filename) {
   AudioMetaData meta = null;
   AudioInputStream ais = getAudioInputStream(filename);
   byte[] samples;
   if (ais != null) {
     AudioFormat format = ais.getFormat();
     if (format instanceof MpegAudioFormat) {
       AudioFormat baseFormat = format;
       format =
           new AudioFormat(
               AudioFormat.Encoding.PCM_SIGNED,
               baseFormat.getSampleRate(),
               16,
               baseFormat.getChannels(),
               baseFormat.getChannels() * 2,
               baseFormat.getSampleRate(),
               false);
       // converts the stream to PCM audio from mp3 audio
       ais = getAudioInputStream(format, ais);
       //	 get a map of properties so we can find out how long it is
       Map<String, Object> props = getID3Tags(filename);
       // there is a property called mp3.length.bytes, but that is
       // the length in bytes of the mp3 file, which will of course
       // be much shorter than the decoded version. so we use the
       // duration of the file to figure out how many bytes the
       // decoded file will be.
       long dur = ((Long) props.get("duration")).longValue();
       int toRead = (int) AudioUtils.millis2Bytes(dur / 1000, format);
       samples = loadByteAudio(ais, toRead);
       meta = new MP3MetaData(filename, dur / 1000, props);
     } else {
       samples = loadByteAudio(ais, (int) ais.getFrameLength() * format.getFrameSize());
       long length = AudioUtils.bytes2Millis(samples.length, format);
       meta = new BasicMetaData(filename, length);
     }
     SourceDataLine line = getSourceDataLine(format, 2048);
     if (line != null) {
       return new JSAudioRecording(this, samples, line, meta);
     }
   }
   return null;
 }
  /**
   * Private method to load audio file
   *
   * @throws LineUnavailableException
   * @throws LineUnavailableException
   * @throws IOException
   * @throws UnsupportedAudioFileException
   */
  private void load() throws LineUnavailableException, UnsupportedAudioFileException, IOException {
    // From URL
    audioStream = AudioSystem.getAudioInputStream(audioURL);

    // At present, ALAW and ULAW encodings must be converted
    // to PCM_SIGNED before it can be played
    AudioFormat audioFormat = audioStream.getFormat();

    DataLine.Info info =
        new DataLine.Info(SourceDataLine.class, audioFormat, AudioSystem.NOT_SPECIFIED);

    if (!AudioSystem.isLineSupported(info)) {
      AudioFormat sourceFormat = audioFormat;
      AudioFormat targetFormat =
          new AudioFormat(
              AudioFormat.Encoding.PCM_SIGNED,
              sourceFormat.getSampleRate(),
              16,
              sourceFormat.getChannels(),
              sourceFormat.getChannels() * (16 / 8),
              sourceFormat.getSampleRate(),
              false);
      audioStream = AudioSystem.getAudioInputStream(targetFormat, audioStream);
      audioFormat = audioStream.getFormat();
    }

    // Create the clip
    info =
        new DataLine.Info(
            Clip.class,
            audioFormat,
            ((int) audioStream.getFrameLength() * audioFormat.getFrameSize()));
    audioClip = (Clip) AudioSystem.getLine(info);

    // Add a listener for line events
    audioClip.addLineListener(this);

    // This method does not return until the audio file is completely
    // loaded
    audioClip.open(audioStream);
  }
Ejemplo n.º 24
0
  private void play(
      AudioInputStream audioInputStream, AudioFormat audioFormat, SourceDataLine dataLine) {
    int bufferSize = (int) audioFormat.getSampleRate() * audioFormat.getFrameSize();
    byte[] buffer = new byte[bufferSize];

    int bytesRead = 0;
    while (true) {
      bytesRead = read(audioInputStream, buffer);
      if (bytesRead == -1) return;

      dataLine.write(buffer, 0, bytesRead);
    }
  }
 private AudioInputStream toLittleEndian(AudioInputStream ais) {
   AudioFormat format = ais.getFormat();
   AudioFormat targetFormat =
       new AudioFormat(
           format.getEncoding(),
           format.getSampleRate(),
           format.getSampleSizeInBits(),
           format.getChannels(),
           format.getFrameSize(),
           format.getFrameRate(),
           false);
   return AudioSystem.getAudioInputStream(targetFormat, ais);
 }
 private void adjustConfigurations(AudioFormat format) {
   int sampleRate = (int) format.getSampleRate();
   int sampleSize = (int) format.getSampleSizeInBits();
   int channels = (int) format.getChannels();
   // int blockSize = sc.getMaxBlockSize();
   /*
    * sc = new StreamConfiguration(channels, blockSize, blockSize,
    * sampleRate, sampleSize);
    */
   sc.setSampleRate(sampleRate);
   sc.setBitsPerSample(sampleSize);
   sc.setChannelCount(channels);
 }
Ejemplo n.º 27
0
 private static Clip loadFile(String path) {
   try {
     path = ClassLoader.getSystemResource(path).getPath();
     path = path.substring(1, path.length()).replaceAll("%20", " ");
     InputStream in = new FileInputStream(path);
     InputStream bin = new BufferedInputStream(in);
     AudioInputStream ais = AudioSystem.getAudioInputStream(bin);
     AudioFormat baseFormat = ais.getFormat();
     AudioFormat decodeFormat =
         new AudioFormat(
             AudioFormat.Encoding.PCM_SIGNED,
             baseFormat.getSampleRate(),
             16,
             baseFormat.getChannels(),
             baseFormat.getChannels() * 2,
             baseFormat.getSampleRate(),
             false);
     AudioInputStream dais = AudioSystem.getAudioInputStream(decodeFormat, ais);
     return AudioSystem.getClip();
   } catch (Exception ex) {
     System.out.println(ex);
   }
   return null;
 }
Ejemplo n.º 28
0
  public boolean load(File file) {

    this.file = file;

    if (file != null && file.isFile()) {
      try {
        errStr = null;
        audioInputStream = AudioSystem.getAudioInputStream(file);

        fileName = file.getName();

        format = audioInputStream.getFormat();

      } catch (Exception ex) {
        reportStatus(ex.toString());
        return false;
      }
    } else {
      reportStatus("Audio file required.");
      return false;
    }

    numChannels = format.getChannels();
    sampleRate = (double) format.getSampleRate();
    sampleBitSize = format.getSampleSizeInBits();
    long frameLength = audioInputStream.getFrameLength();
    long milliseconds = (long) ((frameLength * 1000) / audioInputStream.getFormat().getFrameRate());
    double audioFileDuration = milliseconds / 1000.0;

    if (audioFileDuration > MAX_AUDIO_DURATION) duration = MAX_AUDIO_DURATION;
    else duration = audioFileDuration;

    frameLength = (int) Math.floor((duration / audioFileDuration) * (double) frameLength);

    try {
      audioBytes = new byte[(int) frameLength * format.getFrameSize()];
      audioInputStream.read(audioBytes);
    } catch (Exception ex) {
      reportStatus(ex.toString());
      return false;
    }

    getAudioData();

    return true;
  }
  public void write(AudioInputStream stream, RIFFWriter writer) throws IOException {

    RIFFWriter fmt_chunk = writer.writeChunk("fmt ");

    AudioFormat format = stream.getFormat();
    fmt_chunk.writeUnsignedShort(3); // WAVE_FORMAT_IEEE_FLOAT
    fmt_chunk.writeUnsignedShort(format.getChannels());
    fmt_chunk.writeUnsignedInt((int) format.getSampleRate());
    fmt_chunk.writeUnsignedInt(((int) format.getFrameRate()) * format.getFrameSize());
    fmt_chunk.writeUnsignedShort(format.getFrameSize());
    fmt_chunk.writeUnsignedShort(format.getSampleSizeInBits());
    fmt_chunk.close();
    RIFFWriter data_chunk = writer.writeChunk("data");
    byte[] buff = new byte[1024];
    int len;
    while ((len = stream.read(buff, 0, buff.length)) != -1) data_chunk.write(buff, 0, len);
    data_chunk.close();
  }
 /**
  * Command line interface to the vocal tract linear scaler effect.
  *
  * @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);
 }