Esempio n. 1
1
    public void run() {
      // get line and buffer from ThreadLocals
      SourceDataLine line = (SourceDataLine) localLine.get();
      byte[] buffer = (byte[]) localBuffer.get();
      if (line == null || buffer == null) {
        // the line is unavailable
        return;
      }

      // copy data to the line
      try {
        int numBytesRead = 0;
        while (numBytesRead != -1) {
          // if paused, wait until unpaused
          synchronized (pausedLock) {
            if (paused) {
              try {
                pausedLock.wait();
              } catch (InterruptedException ex) {
                return;
              }
            }
          }
          // copy data
          numBytesRead = source.read(buffer, 0, buffer.length);
          if (numBytesRead != -1) {
            line.write(buffer, 0, numBytesRead);
          }
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
Esempio n. 2
0
 /** Signals that a PooledThread has stopped. Drains and closes the Thread's Line. */
 protected void threadStopped() {
   SourceDataLine line = (SourceDataLine) localLine.get();
   if (line != null) {
     line.drain();
     line.close();
   }
 }
Esempio n. 3
0
  // open up an audio stream
  private static void init() {
    try {
      // 44,100 samples per second, 16-bit audio, mono, signed PCM, little
      // Endian
      AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, false);
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

      line = (SourceDataLine) AudioSystem.getLine(info);
      line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE);

      // the internal buffer is a fraction of the actual buffer size, this
      // choice is arbitrary
      // it gets divided because we can't expect the buffered data to line
      // up exactly with when
      // the sound card decides to push out its samples.
      buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE / 3];
      listeners = new HashSet<AudioEventListener>();
    } catch (Exception e) {
      System.err.println("Error initializing StdAudio audio system:");
      e.printStackTrace();
      System.exit(1);
    }

    // no sound gets made before this call
    line.start();
  }
 public synchronized void start(boolean loop) {
   if (DEBUG || Printer.debug) Printer.debug("> DataPusher.start(loop=" + loop + ")");
   try {
     if (threadState == STATE_STOPPING) {
       // wait that the thread has finished stopping
       if (DEBUG || Printer.trace) Printer.trace("DataPusher.start(): calling stop()");
       stop();
     }
     looping = loop;
     newPos = 0;
     wantedState = STATE_PLAYING;
     if (!source.isOpen()) {
       if (DEBUG || Printer.trace) Printer.trace("DataPusher: source.open()");
       source.open(format);
     }
     if (DEBUG || Printer.trace) Printer.trace("DataPusher: source.flush()");
     source.flush();
     if (DEBUG || Printer.trace) Printer.trace("DataPusher: source.start()");
     source.start();
     if (pushThread == null) {
       if (DEBUG || Printer.debug) Printer.debug("DataPusher.start(): Starting push");
       pushThread =
           JSSecurityManager.createThread(
               this, null, // name
               false, // daemon
               -1, // priority
               true); // doStart
     }
     notifyAll();
   } catch (Exception e) {
     if (DEBUG || Printer.err) e.printStackTrace();
   }
   if (DEBUG || Printer.debug) Printer.debug("< DataPusher.start(loop=" + loop + ")");
 }
Esempio n. 5
0
  public int write(byte[] data, int ofs, int len) {

    int maxTries = 10;
    int totWrite = 0;
    int nofs = ofs, nlen = len;
    while (nofs < ofs + len && maxTries > 0) {

      int written = 0;
      if (format.getBits() == 16 && format.getChannels() == 2 && format.getRate() == INPUT_RATE)
        written = sdl.write(data, nofs, nlen);
      else written = writeConv(data, nofs, nlen);

      nofs += written;
      nlen -= written;
      totWrite += written;
      maxTries--;
      deliveredData += written;

      // calculations when channels and bits and rate varies...
      // int divisor = (format.getBits() / 8) * format.getChannels();
      // int deliveredTime =
      // (int) (1000 * deliveredData / (format.getRate() * divisor));

      int deliveredTime = (int) (1000 * deliveredData / (INPUT_RATE * 4));
      long pos = sdl.getMicrosecondPosition() / 1000;
      long sleepTime = deliveredTime - pos - bufferTime;
      if (sleepTime < 0) sleepTime = 0;

      try {
        Thread.sleep(sleepTime);
      } catch (InterruptedException e) {
      }
    }
    return totWrite;
  }
Esempio n. 6
0
  public SonarSoundEngine(int maxChannels) throws LineUnavailableException {
    silentSample = new SonarSample(new float[] {0}, 44100);
    Mixer mixer = AudioSystem.getMixer(null);

    sdl = (SourceDataLine) mixer.getLine(new Line.Info(SourceDataLine.class));
    sdl.open(new AudioFormat(rate, 16, 2, true, false), bufferSize * 2 * 2 * 2 * 2 * 2);
    soundBuffer.order(ByteOrder.LITTLE_ENDIAN);
    sdl.start();

    try {
      /*            FloatControl volumeControl = (FloatControl) sdl.getControl(FloatControl.Type.MASTER_GAIN);
      volumeControl.setValue(volumeControl.getMaximum());*/
    } catch (IllegalArgumentException e) {
      // System.out.println("Failed to set the sound volume");
    }

    listenerMixer = new ListenerMixer(maxChannels);

    leftBuf = new float[bufferSize];
    rightBuf = new float[bufferSize];

    Thread thread = new Thread(this);
    thread.setDaemon(true);
    thread.setPriority(10);
    thread.start();
  }
Esempio n. 7
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);
  }
Esempio n. 8
0
  public void beginExecution() {

    AudioFormat audioFormat =
        new AudioFormat(
            AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 1, numChannels, 44100.0F, false);
    // System.out.println("AudioPlayer.playAudioInts audio format: " + audioFormat );

    DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
    if (!AudioSystem.isLineSupported(dataLineInfo)) {
      System.out.println("AudioPlayer.playAudioInts does not " + " handle this type of audio.");
      return;
    }

    try {
      SourceDataLine sourceLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);

      sourceLine.open(audioFormat);
    } catch (LineUnavailableException e) {
      e.printStackTrace();
    }

    chunkIndex = 0;

    InitialExecution = true;
  }
Esempio n. 9
0
  public SourceDataLine getOutputLine(AudioFormat format) throws LineUnavailableException {
    SourceDataLine out;

    DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
    out = (SourceDataLine) mixer.getLine(info);
    out.open(format, out.getBufferSize());
    return out;
  }
Esempio n. 10
0
  public void deactivate() {
    active = false;
    microphone.stop();
    microphone.flush();

    speaker.stop();
    speaker.flush();
  }
Esempio n. 11
0
 @Override
 public void onInactive() {
   if (audioLine != null) {
     audioLine.flush();
     audioLine.close();
     audioLine = null;
   }
 }
  public static SourceDataLine getSourceDataLine(AudioFormat format, Mixer.Info mixerinfo)
      throws LineUnavailableException {

    SourceDataLine line =
        (SourceDataLine) getMixer(mixerinfo).getLine(new Line.Info(SourceDataLine.class));
    line.open(format);
    return line;
  }
Esempio n. 13
0
 public void activate() {
   active = true;
   microphone.flush();
   speaker.flush();
   speaker.start();
   blocker.release();
   microphone.start();
   microphone.flush();
 }
Esempio n. 14
0
 public void writeNote(double frequency) {
   byte[] b = new byte[sampleRate];
   for (int i = 0; i < b.length; i++) {
     double r = i / (sampleRate / frequency);
     b[i] = (byte) ((Math.round(r) % 2 == 0) ? 100 : -100);
   }
   // 再生(バイト列をlineに書き込む)
   line.write(b, 0, b.length);
   line.drain(); // 終了まで
 }
Esempio n. 15
0
 public void unMute() {
   if (audioLine == null) {
     isMuted = false;
   } else {
     isMuted = false;
     if (!audioLine.isControlSupported(BooleanControl.Type.MUTE)) return;
     BooleanControl control = (BooleanControl) audioLine.getControl(BooleanControl.Type.MUTE);
     control.setValue(false);
   }
 }
Esempio n. 16
0
 public void mute() {
   if (audioLine == null) {
     isMuted = true;
   } else {
     // when requesting the same line you sometimes get different features
     isMuted = true;
     if (!audioLine.isControlSupported(BooleanControl.Type.MUTE)) return;
     BooleanControl control = (BooleanControl) audioLine.getControl(BooleanControl.Type.MUTE);
     control.setValue(true);
   }
 }
Esempio n. 17
0
 public boolean close() {
   boolean res = true;
   try {
     sdl.stop();
     sdl.close();
   } catch (Exception e) {
     Logger.warning("Could not close or stop SoundDataLine: " + sdl);
     res = false;
   }
   opened = false;
   return res;
 }
Esempio n. 18
0
 public boolean open() {
   boolean res = true;
   opened = true;
   try {
     sdl.open(af);
     sdl.start();
   } catch (Exception e) {
     res = false;
     opened = false;
   }
   return res;
 }
Esempio n. 19
0
 public Oscilator(int sampleRate) {
   this.sampleRate = sampleRate;
   // オーディオ形式を指定
   AudioFormat af = new AudioFormat(sampleRate, 8, 1, true, true);
   try {
     DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
     line = (SourceDataLine) AudioSystem.getLine(info);
     line.open();
     line.start();
   } catch (LineUnavailableException e) {
     e.printStackTrace();
   }
 }
Esempio n. 20
0
 public MakoVM(int[] m) {
   this.m = m;
   try {
     AudioFormat format = new AudioFormat(8000f, 8, 1, false, false);
     DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
     soundLine = (SourceDataLine) AudioSystem.getLine(info);
     soundLine.open(format, 670);
     soundLine.start();
   } catch (IllegalArgumentException e) {
     System.out.println("Unable to initialize sound.");
   } catch (LineUnavailableException e) {
     e.printStackTrace();
   }
 }
Esempio n. 21
0
  public void tick() {
    soundBuffer.clear();

    //        targetAmplitude = (targetAmplitude - 1) * 0.9f + 1;
    //        targetAmplitude = (targetAmplitude - 1) * 0.9f + 1;
    synchronized (listenerMixer) {
      float maxAmplitude = listenerMixer.read(leftBuf, rightBuf, rate);
      //            if (maxAmplitude > targetAmplitude) targetAmplitude = maxAmplitude;
    }

    soundBuffer.clear();
    float gain = 32000;
    for (int i = 0; i < bufferSize; i++) {
      //            amplitude += (targetAmplitude - amplitude) / rate;
      //          amplitude = 1;
      //              float gain = 30000;
      int l = (int) (leftBuf[i] * gain);
      int r = (int) (rightBuf[i] * gain);
      if (l > 32767) l = 32767;
      if (r > 32767) r = 32767;
      if (l < -32767) l = -32767;
      if (r < -32767) r = -32767;
      soundBuffer.putShort((short) l);
      soundBuffer.putShort((short) r);
    }

    sdl.write(soundBuffer.array(), 0, bufferSize * 2 * 2);
  }
Esempio n. 22
0
  @Override
  public void onVolumeChanged(short volume) {
    log.info("apply_volume_callback");
    log.debug("volume: " + volume);
    if (audioLine == null) {
      log.warn("audioLine not ready");
      return;
    }
    FloatControl volumeControl = (FloatControl) audioLine.getControl(FloatControl.Type.MASTER_GAIN);
    float maxDb = volumeControl.getMaximum();
    log.debug("maxDb : " + maxDb);
    float minDbOrig = volumeControl.getMinimum();
    float minDb = minDbOrig + ((maxDb - minDbOrig) / 3);
    log.debug("minDb : " + minDb);
    float newVolume = 0;

    float volumePercent = (float) (volume / 655.35);
    if (volumePercent < 0) {
      volumePercent = 100 + volumePercent;
    }
    log.debug("volume percent : " + volumePercent);
    newVolume = (volumePercent * minDb / 100);
    newVolume = (newVolume - minDb) * -1;

    if (volume == 0) {
      log.debug("volume 0, setting max");
      newVolume = minDbOrig;
    }

    log.debug("newVolume : " + newVolume);
    volumeControl.setValue(newVolume);
  }
Esempio n. 23
0
  private void init() {

    AudioFormat format = new AudioFormat((float) 44100, 16, 2, true, false);
    try {
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
      mainLine = (SourceDataLine) AudioSystem.getLine(info);
      mainLine.open(format);
      mainLine.start();

      bufferLine = (SourceDataLine) AudioSystem.getLine(info);
      bufferLine.open(format);
      bufferLine.start();

    } catch (LineUnavailableException e) {
      e.printStackTrace();
    }
  }
Esempio n. 24
0
  public static void bang() throws LineUnavailableException, InterruptedException {
    AudioFormat af =
        new AudioFormat(
            SAMPLE_RATE, // sampleRate
            8, // sampleSizeInBits
            1, // channels
            true, // signed
            false); // bigEndian
    SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
    sdl.open(af);
    sdl.start();

    byte[] buf = new byte[1];
    Random r = new Random();
    boolean silence = true;
    for (int i = 0; i < 8000; i++) {
      while (r.nextInt() % 10 != 0) {
        buf[0] =
            silence
                ? 0
                : (byte)
                    Math.abs(
                        r.nextInt()
                            % (int) (1. + 63. * (1. + Math.cos(((double) i) * Math.PI / 8000.))));
        i++;
        sdl.write(buf, 0, 1);
      }
      silence = !silence;
    }
    sdl.drain();
    sdl.stop();
    sdl.close();
  }
Esempio n. 25
0
  public static void warp(int repeat) throws LineUnavailableException, InterruptedException {
    AudioFormat af =
        new AudioFormat(
            SAMPLE_RATE, // sampleRate
            8, // sampleSizeInBits
            1, // channels
            true, // signed
            false); // bigEndian
    SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
    sdl.open(af);
    sdl.start();

    byte[] buf = new byte[1];
    int step;

    for (int j = 0; j < repeat; j++) {
      step = 25;
      for (int i = 0; i < 2000; i++) {
        if (i < 500) {
          buf[0] = ((i % step > 0) ? 32 : (byte) 0);
          if (i % 25 == 0) step--;
        } else {
          buf[0] = ((i % step > 0) ? 16 : (byte) 0);
          if (i % 50 == 0) step++;
        }
        sdl.write(buf, 0, 1);
      }
    }
    sdl.drain();
    sdl.stop();
    sdl.close();
  }
Esempio n. 26
0
 /** 列に周波数とバイト列の長さ指定で形を書き込む */
 public void writeNote(double frequency, int sampleCount) {
   byte[] b = new byte[sampleRate];
   double amplitude = sampleRate / frequency; // 波長
   for (int i = 0; i < b.length; i++) {
     double r = i / amplitude;
     b[i] = (byte) ((Math.round(r) % 2 == 0) ? 100 : -100);
   } // 再生(バイト列をlineに書き込む)
   line.write(b, 0, b.length);
 }
Esempio n. 27
0
  @Override
  public void onActive() {
    if (audioLine != null) audioLine.close();

    try {
      if (player.getMixer() != null) {
        log.debug("Custom mixer " + player.getMixer().getName());
        audioLine = AudioSystem.getSourceDataLine(PCM, player.getMixer());
      } else {
        audioLine = AudioSystem.getSourceDataLine(PCM);
      }
      audioLine.open(PCM, 1048576);
      onVolumeChanged(player.getVolume());
      if (isMuted && audioLine.isControlSupported(BooleanControl.Type.MUTE))
        ((BooleanControl) audioLine.getControl(BooleanControl.Type.MUTE)).setValue(true);
    } catch (LineUnavailableException e) {
      log.error("onActive error", e);
    }
  }
Esempio n. 28
0
  @Override
  public void run() {
    try {
      AudioFormat format = settings.getAudioFormat();
      DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, format);
      SourceDataLine speakers = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
      speakers.open(format);
      speakers.start();
      byte[] data = new byte[204800];

      while (!Thread.interrupted()) {
        int numBytesRead = receiver.getInputStream().read(data, 0, 1024);
        log.debug("[Player] received {} bytes", numBytesRead);
        speakers.write(data, 0, numBytesRead);
      }
    } catch (LineUnavailableException | IOException e) {
      log.error("[Player] error occurred", e);
    }
  }
Esempio n. 29
0
 public void doFade(SourceDataLine line, final double to) {
   final FloatControl gainControl = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
   new Thread(
           new Runnable() {
             @Override
             public void run() {
               fade(gainControl, to);
             }
           })
       .start();
 }
Esempio n. 30
0
 /** バイト列に周波数、ベロシティ指定で波形書き込む */
 public void writeWave(byte[] b, double frequency, int velocity) {
   double amplitude = sampleRate / frequency; // 波長
   for (int i = 0; i < b.length; i++) {
     double r = i / amplitude;
     int v = (byte) ((Math.round(r) % 2 == 0) ? velocity : -velocity);
     v += b[i];
     v = Math.min(Math.max(v, -128), 127);
     b[i] = (byte) v;
   }
   // 再生(バイト列をlineに書き込む)
   line.write(b, 0, b.length);
 }