Beispiel #1
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();
 }
Beispiel #2
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 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();
  }
Beispiel #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);
  }
Beispiel #5
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();
  }
Beispiel #6
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();
  }
  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;
  }
 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 + ")");
 }
Beispiel #9
0
  public void run() {
    try {
      AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
      AudioFormat format = ais.getFormat();
      //    System.out.println("Format: " + format);
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
      SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info);
      source.open(format);
      source.start();
      int read = 0;
      byte[] audioData = new byte[16384];
      while (read > -1) {
        read = ais.read(audioData, 0, audioData.length);
        if (read >= 0) {
          source.write(audioData, 0, read);
        }
      }
      donePlaying = true;

      source.drain();
      source.close();
    } catch (Exception exc) {
      System.out.println("error: " + exc.getMessage());
      exc.printStackTrace();
    }
  }
Beispiel #10
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;
  }
  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;
  }
Beispiel #12
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();
    }
  }
Beispiel #13
0
 public boolean open() {
   boolean res = true;
   opened = true;
   try {
     sdl.open(af);
     sdl.start();
   } catch (Exception e) {
     res = false;
     opened = false;
   }
   return res;
 }
Beispiel #14
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();
   }
 }
Beispiel #15
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();
   }
 }
Beispiel #16
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);
    }
  }
  @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);
    }
  }
Beispiel #18
0
  // 播放au,aiff,wav音乐流, 这个函数基本完全为帖子上的代码
  private synchronized void play() {
    ByteArrayInputStream aMusicInputStream;
    AudioFormat format;
    AudioInputStream musicInputStream;
    byte[] audioSamples;
    SourceDataLine line;
    try {
      File MusicFile = new File(m_filename);

      musicInputStream = AudioSystem.getAudioInputStream(MusicFile); // 取得文件的音频输入流
      format = musicInputStream.getFormat(); // 取得音频输入流的格式
      audioSamples = getAudioSamples(musicInputStream, format); // 取得音频样本

      aMusicInputStream = new ByteArrayInputStream(audioSamples);
      int bufferSize = format.getFrameSize() * Math.round(format.getSampleRate() / 10);
      byte[] buffer = new byte[bufferSize];
      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;
      }

      if (!line.isRunning()) {
        line.start();
      }

      int numBytesRead = 0;
      while (numBytesRead != -1 && !m_stopped) {
        numBytesRead = aMusicInputStream.read(buffer, 0, buffer.length);
        if (numBytesRead != -1) {
          line.write(buffer, 0, numBytesRead);
        }
      }
      line.drain();
      line.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #19
0
 public static void tone(int hz, int msecs, double vol) throws LineUnavailableException {
   byte[] buf = new byte[1];
   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();
   for (int i = 0; i < msecs * 8; i++) {
     double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
     buf[0] = (byte) (Math.sin(angle) * 127.0 * vol);
     sdl.write(buf, 0, 1);
   }
   sdl.drain();
   sdl.stop();
   sdl.close();
 }
 public void run() {
   SourceDataLine line = null;
   try {
     try {
       line = (SourceDataLine) AudioSystem.getLine(new DataLine.Info(SourceDataLine.class, fmt));
       line.open(fmt, bufsize);
       line.start();
     } catch (Exception e) {
       e.printStackTrace();
       return;
     }
     byte[] buf = new byte[1024];
     //noinspection InfiniteLoopStatement
     while (true) {
       if (Thread.interrupted()) throw (new InterruptedException());
       synchronized (queuemon) {
         Collection<Runnable> queue = Audio.queue;
         Audio.queue = new LinkedList<Runnable>();
         for (Runnable r : queue) r.run();
       }
       synchronized (ncl) {
         for (CS cs : ncl) clips.add(cs);
         ncl.clear();
       }
       fillbuf(buf, 0, 1024);
       //noinspection StatementWithEmptyBody
       for (int off = 0; off < buf.length; off += line.write(buf, off, buf.length - off)) ;
     }
   } catch (InterruptedException ignored) {
   } finally {
     synchronized (Audio.class) {
       player = null;
     }
     if (line != null) line.close();
   }
 }
  public void run() {
    try {
      AudioFormat audioFormat = audioInputStream.getFormat();
      DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
      SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
      sourceDataLine.open(audioFormat);
      sourceDataLine.start();

      int cnt;
      while ((cnt = audioInputStream.read(tempBuffer, 0, tempBuffer.length)) != -1) {
        if (cnt > 0) {
          sourceDataLine.write(tempBuffer, 0, cnt);
        }
      }
      sourceDataLine.drain();
      sourceDataLine.stop();
      sourceDataLine.close();
      sourceDataLine.close();
      audioInputStream.close();
    } catch (Exception e) {
      System.out.println("jMusic AudioFilePlayThread error");
      e.printStackTrace();
    }
  }