Example #1
0
 SourceDataLine getSourceDataLine(AudioFormat format, int bufferSize) {
   SourceDataLine line = null;
   DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
   if (AudioSystem.isLineSupported(info)) {
     try {
       if (outputMixer == null) {
         line = (SourceDataLine) AudioSystem.getLine(info);
       } else {
         line = (SourceDataLine) outputMixer.getLine(info);
       }
       // remember that time you spent, like, an entire afternoon fussing
       // with this buffer size to try to get the latency decent on Linux?
       // Yah, don't fuss with this anymore, ok?
       line.open(format, bufferSize * format.getFrameSize() * 4);
       if (line.isOpen()) {
         debug(
             "SourceDataLine is "
                 + line.getClass().toString()
                 + "\n"
                 + "Buffer size is "
                 + line.getBufferSize()
                 + " bytes.\n"
                 + "Format is "
                 + line.getFormat().toString()
                 + ".");
         return line;
       }
     } catch (LineUnavailableException e) {
       error("Couldn't open the line: " + e.getMessage());
     }
   }
   error("Unable to return a SourceDataLine: unsupported format - " + format.toString());
   return line;
 }
Example #2
0
 TargetDataLine getTargetDataLine(AudioFormat format, int bufferSize) {
   TargetDataLine line = null;
   DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
   if (AudioSystem.isLineSupported(info)) {
     try {
       if (inputMixer == null) {
         line = (TargetDataLine) AudioSystem.getLine(info);
       } else {
         line = (TargetDataLine) inputMixer.getLine(info);
       }
       line.open(format, bufferSize * format.getFrameSize());
       debug(
           "TargetDataLine buffer size is "
               + line.getBufferSize()
               + "\n"
               + "TargetDataLine format is "
               + line.getFormat().toString()
               + "\n"
               + "TargetDataLine info is "
               + line.getLineInfo().toString());
     } catch (Exception e) {
       error("Error acquiring TargetDataLine: " + e.getMessage());
     }
   } else {
     error("Unable to return a TargetDataLine: unsupported format - " + format.toString());
   }
   return line;
 }
Example #3
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];
     }
   }
 }
Example #4
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);
  }
 /** @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;
 }
Example #6
0
  private void doPlay(File file) {
    AudioInputStream actualAudioIn = null;
    this.file = file;
    try (AudioInputStream audioIn = AudioSystem.getAudioInputStream(file)) {
      AudioFormat baseFormat = audioIn.getFormat();
      System.out.println(baseFormat.getEncoding());
      AudioFormat decodedFormat = getDecodedFormat(baseFormat);

      // make new audio in stream based on decoded format
      actualAudioIn = AudioSystem.getAudioInputStream(decodedFormat, audioIn);

      // get data from audio system
      line = getLine(decodedFormat);

      line.addLineListener(this);

      doPlay(decodedFormat, actualAudioIn);
      audioIn.close();
    } catch (Exception e) {
      logger.log(Level.WARNING, "Exception playing file '" + file.getName() + "'", e);
    } finally {
      if (actualAudioIn != null) {
        try {
          actualAudioIn.close();
        } catch (IOException e) {
        }
      }
      if (line != null) line.close();
    }
  }
Example #7
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();
 }
 /**
  * Construct an audio input stream from which <code>duration</code> seconds of silence can be
  * read.
  *
  * @param duration the desired duration of the silence, in seconds
  * @param format the desired audio format of the audio input stream. getFrameSize() and
  *     getFrameRate() must return meaningful values.
  */
 public SilenceAudioInputStream(double duration, AudioFormat format) {
   super(
       new ByteArrayInputStream(
           new byte[(int) (format.getFrameSize() * format.getFrameRate() * duration)]),
       format,
       (long) (format.getFrameRate() * duration));
 }
Example #9
0
  /**
   * load the desired sound data into memory.
   *
   * @param filename
   * @return
   * @throws IOException
   * @throws UnsupportedAudioFileException
   */
  private GameSoundData loadSound(String filename)
      throws IOException, UnsupportedAudioFileException {
    // should find sounds placed in root of jar file, which build file should do;
    // in an ide, setting should be tweaked to see audio dir as on path.
    // (e.g., in eclipse, run -> debug configs -> classpath -> add folder,
    //  or place audio files in root of runtime dir, likely "bin")
    InputStream is = this.getClass().getClassLoader().getResourceAsStream(filename);
    is = new BufferedInputStream(is);

    AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(is);
    AudioInputStream ais = AudioSystem.getAudioInputStream(is);

    AudioFormat audioFormat = fileFormat.getFormat();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int bufSize = BUFLEN * audioFormat.getFrameSize();
    byte[] byteBuf = new byte[bufSize];
    while (true) {
      int nRead = ais.read(byteBuf);
      if (nRead == -1) break;
      baos.write(byteBuf, 0, nRead);
    }
    ;
    ais.close();
    is.close();
    GameSoundData gsd = new GameSoundData();
    gsd.format = audioFormat;
    gsd.rawData = baos.toByteArray();
    baos.close();
    return gsd;
  }
Example #10
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();
      }
    }
Example #11
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());
 }
Example #12
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;
 }
Example #13
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);
 }
Example #14
0
 public AudioFormat[] getTargetFormats(
     AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat) {
   if ((AudioFormat.Encoding.PCM_SIGNED.equals(targetEncoding)
           && AudioFormat.Encoding.ULAW.equals(sourceFormat.getEncoding()))
       || (AudioFormat.Encoding.ULAW.equals(targetEncoding)
           && AudioFormat.Encoding.PCM_SIGNED.equals(sourceFormat.getEncoding()))) {
     return getOutputFormats(sourceFormat);
   } else {
     return new AudioFormat[0];
   }
 }
Example #15
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());
    }
  }
Example #16
0
  /*  public AudioInputStream getConvertedStream(AudioFormat outputFormat, AudioInputStream stream) { */
  private AudioInputStream getConvertedStream(AudioFormat outputFormat, AudioInputStream stream) {
    AudioInputStream cs = null;

    AudioFormat inputFormat = stream.getFormat();

    if (inputFormat.matches(outputFormat)) {
      cs = stream;
    } else {
      cs = (AudioInputStream) (new UlawCodecStream(stream, outputFormat));
    }
    return cs;
  }
 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);
 }
  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);
    }
  }
Example #19
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);
    }
  }
Example #20
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);
 }
Example #21
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);
 }
Example #22
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();
    }
  }
Example #23
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);
 }
 @Override
 public void iniciouLeituraSom(AudioFormat format) {
   this.sampleRate = format.getFrameRate();
   this.idxTempo = 0;
   this.listaFrequenciasTempo = new ArrayList<FrequenciasSomTempo>();
   this.dadosAmostra = new double[0];
 }
Example #25
0
 @Override
 public int hashCode() {
   int result = audioFormat != null ? audioFormat.hashCode() : 0;
   result = 31 * result + (realData != null ? Arrays.hashCode(realData) : 0);
   result = 31 * result + frameNumber;
   return result;
 }
 /** Inits Audio ressources from AudioSystem.<br> */
 protected void initLine() throws LineUnavailableException {
   log.info("initLine()");
   if (m_line == null) {
     createLine();
   }
   if (!m_line.isOpen()) {
     openLine();
   } else {
     AudioFormat lineAudioFormat = m_line.getFormat();
     AudioFormat audioInputStreamFormat =
         m_audioInputStream == null ? null : m_audioInputStream.getFormat();
     if (!lineAudioFormat.equals(audioInputStreamFormat)) {
       m_line.close();
       openLine();
     }
   }
 }
Example #27
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;
 }
Example #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;
  }
 /**
  * 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();
 }
Example #30
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);
  }