public static void main(String[] args) throws Exception {
    SoftSynthesizer synth = new SoftSynthesizer();
    synth.openStream(new AudioFormat(44100, 16, 1, true, false), null);

    SoftAudioBuffer in1 = new SoftAudioBuffer(250, synth.getFormat());
    SoftAudioBuffer out1 = new SoftAudioBuffer(250, synth.getFormat());

    float[] testdata1 = new float[in1.getSize()];
    float[] n1a = in1.array();
    float[] out1a = out1.array();
    for (int i = 0; i < n1a.length; i++) {
      testdata1[i] = (float) Math.sin(i * 0.3) * 0.9f;
      n1a[i] = testdata1[i];
      out1a[i] = 1;
    }

    SoftLimiter limiter = new SoftLimiter();
    limiter.init(44100, 147);
    limiter.setMixMode(false);
    limiter.setInput(0, in1);
    limiter.setOutput(0, out1);
    limiter.processControlLogic();
    limiter.processAudio();
    limiter.processControlLogic();
    limiter.processAudio();
    // Limiter should delay audio by one buffer,
    // and there should almost no different in output v.s. input
    for (int i = 0; i < n1a.length; i++) {
      if (Math.abs(out1a[i] - testdata1[i]) > 0.00001) throw new Exception("input != output");
    }

    synth.close();
  }
Exemplo n.º 2
0
  /**
   * This is only for testing/debugging, Tries to play a genereated sound.
   *
   * @param args
   */
  public static void main(String[] args) {
    try {
      int rate = INPUT_RATE;
      byte[] data = new byte[10 * 2 * 2 * rate];
      for (int n = 0; n < data.length; n += 4) {
        // double pan = Math.sin(n * 2 * 3.14 / (rate * 5)) * 0.5 + 0.5;
        int s1 = (int) (Math.sin(n * 2 * 3.14 * 100 / rate) * 32767);
        int s2 = (int) (Math.sin(n * 2 * 3.14 * 100 / rate) * 32767);
        // int c1 = (int) (s1 * pan + s2 * (1 - pan));
        // int c2 = (int) (s2 * pan + s1 * (1 - pan));
        data[n + 0] = (byte) s1;
        data[n + 1] = (byte) (s1 >>> 8);
        data[n + 2] = (byte) s2;
        data[n + 3] = (byte) (s2 >>> 8);
      }
      SoundDataFormat sdf = new SoundDataFormat(8, rate, 2);
      JavaSoundOutput sso = new JavaSoundOutput(sdf, 300);

      boolean ok = true;

      ok = sso.open();
      if (!ok) throw new Exception("init");

      for (int n = 0; n < data.length; n += 8000) sso.write(data, n, 8000);

      ok = sso.close();
      if (!ok) throw new Exception("init");

    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Exemplo n.º 3
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();
  }
Exemplo n.º 4
0
  public void reset() {

    // init the location of the rocket to the center.
    rocketXPos = getWidth2() / 2;
    rocketYPos = getHeight2() / 2;
    // rocket direction
    rocketRight = true;
    // rocket speed.
    rocketXSpeed = 0;
    rocketYSpeed = 0;
    rocketMaxSpeed = 10;
    // rocket lives
    rocketLife = 3;
    // star position.
    starXPos = new int[numStars];
    starYPos = new int[numStars];
    starActive = new boolean[numStars];

    for (int index = 0; index < numStars; index++) {
      starXPos[index] = (int) (Math.random() * getWidth2());
      starYPos[index] = (int) (Math.random() * getHeight2());
      starActive[index] = true;
    }
    // score stuff
    score = 0;
    // missile stuff
    missile = new Missile[Missile.numMissile];
    for (int index = 0; index < missile.length; index++) {
      missile[index] = new Missile();
    }
    Missile.currentIndex = 0;
    starHit = -1;
    gameOver = false;
  }
  static void setUp() throws Exception {
    testarray = new float[1024];
    for (int i = 0; i < 1024; i++) {
      double ii = i / 1024.0;
      ii = ii * ii;
      testarray[i] = (float) Math.sin(10 * ii * 2 * Math.PI);
      testarray[i] += (float) Math.sin(1.731 + 2 * ii * 2 * Math.PI);
      testarray[i] += (float) Math.sin(0.231 + 6.3 * ii * 2 * Math.PI);
      testarray[i] *= 0.3;
    }
    test_byte_array = new byte[testarray.length * 2];
    AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array);
    buffer = new ModelByteBuffer(test_byte_array);

    byte[] test_byte_array2 = new byte[testarray.length * 3];
    buffer24 = new ModelByteBuffer(test_byte_array2);
    test_byte_array_8ext = new byte[testarray.length];
    byte[] test_byte_array_8_16 = new byte[testarray.length * 2];
    AudioFloatConverter.getConverter(format24).toByteArray(testarray, test_byte_array2);
    int ix = 0;
    int x = 0;
    for (int i = 0; i < test_byte_array_8ext.length; i++) {
      test_byte_array_8ext[i] = test_byte_array2[ix++];
      test_byte_array_8_16[x++] = test_byte_array2[ix++];
      test_byte_array_8_16[x++] = test_byte_array2[ix++];
    }
    buffer16_8 = new ModelByteBuffer(test_byte_array_8_16);
    buffer8 = new ModelByteBuffer(test_byte_array_8ext);

    AudioInputStream ais = new AudioInputStream(buffer.getInputStream(), format, testarray.length);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    AudioSystem.write(ais, AudioFileFormat.Type.WAVE, baos);
    buffer_wave = new ModelByteBuffer(baos.toByteArray());
  }
Exemplo n.º 6
0
  public boolean transform(ProgressListener progressListener) {

    toneMap = toneMapFrame.getToneMap();
    timeSet = toneMap.getTimeSet();
    pitchSet = toneMap.getPitchSet();
    timeRange = timeSet.getRange();
    pitchRange = pitchSet.getRange();

    pitchFreqSet = pitchSet.getFreqSet();
    audioFTPower = new double[timeRange * (pitchRange + 1)];

    int startSample = timeSet.getStartSample();
    int endSample = timeSet.getEndSample();
    int sampleLength = (int) Math.floor((endSample - startSample) / ((double) resolution));
    double[] audioSamples = new double[sampleLength];

    for (int i = 0; i < sampleLength; i++) {
      audioSamples[i] = (double) audioData[startSample + i * resolution];
    }

    int sampleIndexSize =
        (int) Math.floor((double) timeSet.getSampleIndexSize() / (double) resolution);

    double dt = (double) resolution / sampleRate;
    if (transformMode == TRANSFORM_MODE_JAVA) {
      wavelet.convert(
          audioFTPower,
          audioSamples,
          pitchFreqSet,
          dt,
          (double) pFactor,
          (double) tFactor,
          sampleIndexSize,
          sampleLength,
          pitchRange,
          progressListener);
    } else {

      WaveletJNI waveletJNI = new WaveletJNI();

      waveletJNI.waveletConvert(
          audioFTPower,
          audioSamples,
          pitchFreqSet,
          dt,
          (double) pFactor,
          (double) tFactor,
          sampleIndexSize,
          sampleLength,
          pitchRange,
          progressListener);
    }

    return true;
  }
Exemplo n.º 7
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);
 }
Exemplo n.º 8
0
 public static BufferedImage scaleImage(BufferedImage bi, double scale) {
   int w1 = (int) (Math.round(scale * bi.getWidth()));
   int h1 = (int) (Math.round(scale * bi.getHeight()));
   BufferedImage image = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);
   Graphics2D g2 = image.createGraphics();
   g2.setRenderingHint(
       RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
   g2.setPaint(Color.white);
   g2.fillRect(0, 0, w1, h1);
   g2.drawImage(bi, 0, 0, w1, h1, null); // this);
   g2.dispose();
   return image;
 }
Exemplo n.º 9
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();
 }
Exemplo n.º 10
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);
  }
Exemplo n.º 11
0
 static void setUp() throws Exception {
   testarray = new float[1024];
   for (int i = 0; i < 1024; i++) {
     double ii = i / 1024.0;
     ii = ii * ii;
     testarray[i] = (float) Math.sin(10 * ii * 2 * Math.PI);
     testarray[i] += (float) Math.sin(1.731 + 2 * ii * 2 * Math.PI);
     testarray[i] += (float) Math.sin(0.231 + 6.3 * ii * 2 * Math.PI);
     testarray[i] *= 0.3;
   }
   test_byte_array = new byte[testarray.length * 2];
   AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array);
   test_file = File.createTempFile("test", ".raw");
   FileOutputStream fos = new FileOutputStream(test_file);
   fos.write(test_byte_array);
 }
Exemplo n.º 12
0
 /**
  * Create a note (sine wave) of the given frequency (Hz), for the given duration (seconds) scaled
  * to the given volume (amplitude).
  */
 public static double[] note(double hz, double duration, double amplitude) {
   int N = (int) (StdAudio.SAMPLE_RATE * duration);
   double[] a = new double[N + 1];
   for (int i = 0; i <= N; i++)
     a[i] = amplitude * Math.sin(2 * Math.PI * i * hz / StdAudio.SAMPLE_RATE);
   return a;
 }
Exemplo n.º 13
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);
 }
Exemplo n.º 14
0
  public boolean play() {

    try {
      if (playState != STOPPED) playStop();

      if (audioBytes == null) return false;

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

      clip = (Clip) AudioSystem.getLine(info);
      clip.addLineListener(new ClipListener());

      long clipStart = (long) (audioBytes.length * getStartTime() / (getDuration() * 1000.0));
      long clipEnd = (long) (audioBytes.length * getEndTime() / (getDuration() * 1000.0));
      if ((clipEnd - clipStart) > MAX_CLIP_LENGTH) clipEnd = clipStart + MAX_CLIP_LENGTH;
      byte[] clipBytes = new byte[(int) (clipEnd - clipStart)];
      System.arraycopy(audioBytes, (int) clipStart, clipBytes, 0, clipBytes.length);
      clip.open(format, clipBytes, 0, clipBytes.length);

      FloatControl panControl = (FloatControl) clip.getControl(FloatControl.Type.PAN);

      panControl.setValue((float) panSetting / 100.0f);

      double value = (double) gainSetting;

      FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
      float dB = (float) (Math.log(value == 0.0 ? 0.0001 : value) / Math.log(10.0) * 20.0);
      gainControl.setValue(dB);
      double playStartTime = (player.getSeekTime() / 100) * (playGetLength());
      clip.setMicrosecondPosition((long) playStartTime);

      clip.start();

      playState = PLAYING;

      return true;

    } catch (Exception ex) {
      ex.printStackTrace();
      playState = STOPPED;
      clip = null;
      return false;
    }
  }
Exemplo n.º 15
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(); // 終了まで
 }
Exemplo n.º 16
0
 /** Creates a new SoundManager with the specified maximum number of simultaneous sounds. */
 public SoundManager(AudioFormat playbackFormat, int maxSimultaneousSounds) {
   super(Math.min(maxSimultaneousSounds, getMaxSimultaneousSounds(playbackFormat)));
   this.playbackFormat = playbackFormat;
   localLine = new ThreadLocal();
   localBuffer = new ThreadLocal();
   pausedLock = new Object();
   // notify threads in pool it's ok to start
   synchronized (this) {
     notifyAll();
   }
 }
Exemplo n.º 17
0
 private static void playWav(String name, boolean loop, double volume)
     throws FileNotFoundException, IOException, UnsupportedAudioFileException,
         LineUnavailableException {
   AudioInputStream ais = AudioSystem.getAudioInputStream(new File(path + name));
   Clip clip = AudioSystem.getClip();
   clip.open(ais);
   if (loop) {
     clip.loop(-1);
   }
   ((FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN))
       .setValue((float) (Math.log(volume) / Math.log(10.) * 20.));
   clip.start();
   wavMap.put(name, clip);
   //        // open the sound file as a Java input stream
   //        InputStream in = new FileInputStream(path + name);
   //        // create an audiostream from the inputstream
   //        AudioStream audioStream = new AudioStream(in);
   //        // play the audio clip with the audioplayer class
   //        AudioPlayer.player.start(audioStream);
   //        wavMap.put(name, audioStream);
 }
 private static void playres(Resource res) {
   Collection<Resource.Audio> clips = res.layers(Resource.audio);
   int s = (int) (Math.random() * clips.size());
   Resource.Audio clip = null;
   for (Resource.Audio cp : clips) {
     clip = cp;
     if (--s < 0) break;
   }
   if (clip != null) {
     play(clip.clip);
   }
 }
Exemplo n.º 19
0
  /** Test client - play an A major scale to standard audio. */
  public static void main(String[] args) {
    // 440 Hz for 1 sec
    double freq = 440.0;
    for (int i = 0; i <= StdAudio.SAMPLE_RATE; i++) {
      StdAudio.play(0.5 * Math.sin(2 * Math.PI * freq * i / StdAudio.SAMPLE_RATE));
    }

    // scale increments
    int[] steps = {0, 2, 4, 5, 7, 9, 11, 12};
    for (int i = 0; i < steps.length; i++) {
      double hz = 440.0 * Math.pow(2, steps[i] / 12.0);
      StdAudio.play(note(hz, 1.0, 0.5));
    }

    // need to call this in non-interactive stuff so the program doesn't
    // terminate
    // until all the sound leaves the speaker.
    StdAudio.close();

    // need to terminate a Java program with sound
    System.exit(0);
  }
Exemplo n.º 20
0
  private void fade(FloatControl control, double to) {
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (control) {
      int steps = FADE_DURATION / FADE_STEP_DURATION;

      to = (to <= 0.0) ? 0.0001 : ((to > 1.0) ? 1.0 : to);

      float currDB = control.getValue();
      float toDB = getDb(to);

      float diffStep = (toDB - currDB) / (float) steps;
      for (int i = 0; i < steps; i++) {
        currDB += diffStep;
        currDB = (Math.abs(currDB - toDB) < Math.abs(diffStep * 1.5)) ? toDB : currDB;
        control.setValue(currDB);
        try {
          Thread.sleep(FADE_STEP_DURATION);
        } catch (Exception ignored) {
          ignored.printStackTrace();
        }
      }
    }
  }
Exemplo n.º 21
0
 @Override
 public int onAudioData(byte[] data) {
   if (audioLine != null && audioLine.isOpen()) {
     if (!audioLine.isRunning()) {
       audioLine.start();
     }
     int toWrite = Math.min(audioLine.available(), data.length);
     if (toWrite == audioLine.available())
       log.trace("full! toWrite: " + toWrite + " instead of: " + data.length);
     return audioLine.write(data, 0, toWrite);
   } else {
     return 0;
   }
 }
Exemplo n.º 22
0
  public void reset() {

    // init the location of the rocket to the center.
    rocketXPos = getWidth2() / 2;
    rocketYPos = getHeight2() / 2;
    star = new Star[starNum];
    missle = new Missle[missleNum];
    firsttouch = new boolean[starNum];
    for (int i = 0; i < starNum; i++) {
      star[i] = new Star(20, 20);
      star[i].setXPos((int) (Math.random() * getWidth2()));
      star[i].setYPos((int) (Math.random() * getHeight2()));
      while (star[i].getLeftSide() < rocketXPos + Rocketwidth / 2
          && star[i].getRightSide() > rocketXPos - Rocketwidth / 2
          && star[i].getTop() > rocketYPos - Rocketheight / 2
          && star[i].getBottom() < rocketYPos + Rocketheight / 2) {
        star[i].setXPos((int) (Math.random() * getWidth2()));
        star[i].setYPos((int) (Math.random() * getHeight2()));
      }
      firsttouch[i] = false;
    }
    speed = 0;

    for (int i = 0; i < missle.length; i++) {
      missle[i] = new Missle(10, 10);
    }
    missleIndex = 0;

    Rocketwidth = rocketImage.getWidth(this);
    Rocketheight = rocketImage.getHeight(this);
    score = 0;
    lives = 3;
    GameOver = false;

    ff = false;
    ffwidth = 25;
  }
Exemplo n.º 23
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;
  }
Exemplo n.º 24
0
  private static WAVData readFromStream(AudioInputStream aIn)
      throws UnsupportedAudioFileException, IOException {
    ReadableByteChannel aChannel = Channels.newChannel(aIn);
    AudioFormat fmt = aIn.getFormat();
    int numChannels = fmt.getChannels();
    int bits = fmt.getSampleSizeInBits();
    int format = AL_FORMAT_MONO8;

    if ((bits == 8) && (numChannels == 1)) {
      format = AL_FORMAT_MONO8;
    } else if ((bits == 16) && (numChannels == 1)) {
      format = AL_FORMAT_MONO16;
    } else if ((bits == 8) && (numChannels == 2)) {
      format = AL_FORMAT_STEREO8;
    } else if ((bits == 16) && (numChannels == 2)) {
      format = AL_FORMAT_STEREO16;
    }

    int freq = Math.round(fmt.getSampleRate());
    int size = aIn.available();
    ByteBuffer buffer = ByteBuffer.allocateDirect(size);
    while (buffer.remaining() > 0) {
      aChannel.read(buffer);
    }
    buffer.rewind();

    // Must byte swap on big endian platforms
    // Thanks to swpalmer on javagaming.org forums for hint at fix
    if ((bits == 16) && (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN)) {
      int len = buffer.remaining();
      for (int i = 0; i < len; i += 2) {
        byte a = buffer.get(i);
        byte b = buffer.get(i + 1);
        buffer.put(i, b);
        buffer.put(i + 1, a);
      }
    }

    WAVData result = new WAVData(buffer, format, size, freq, false);
    aIn.close();

    return result;
  }
Exemplo n.º 25
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();
    }
  }
Exemplo n.º 26
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();
 }
Exemplo n.º 27
0
  // Transitions from Overworld to Battle scene
  public void battleBegin() {
    scene = BATTLE;
    moveUp = false;
    moveDown = false;
    moveLeft = false;
    moveRight = false;

    // Background changer
    int bgSelector = (int) (10 * Math.random() + 1);
    if (bgSelector > 5) {
      ImageIcon bg = new ImageIcon("BattleBG1.jpg");
      background = bg.getImage();
      battleBG = 1;
      player.battleBegin(235, 380);
      int placed = 0;
      for (int enemyNum = 0; enemyNum < enemies.size(); enemyNum++) {
        Enemy enemy = enemies.get(enemyNum);
        if (enemy.getActivity()) {
          enemy.battleBegin(440 - 20 * placed, 125);
          placed++;
          totalExperience += enemy.getEXP();
        }
      }
    } else {
      ImageIcon bg = new ImageIcon("BattleBG2.png");
      background = bg.getImage();
      battleBG = 2;
      player.battleBegin(650, 365);
      int placed = 0;
      for (int loop = 0; loop < enemies.size(); loop++) {
        if (enemies.get(loop).getActivity()) {
          enemies.get(loop).battleBegin(340 - 20 * placed, 145);
          placed++;
          totalExperience += enemies.get(loop).getEXP();
        }
      }
    }
    menuScreen.setVisible(false);
    staminaTimer.start();
  }
Exemplo n.º 28
0
  public void animate() {
    if (animateFirstTime) {
      animateFirstTime = false;
      if (xsize != getSize().width || ysize != getSize().height) {
        xsize = getSize().width;
        ysize = getSize().height;
      }
      readFile();
      outerSpaceImage = Toolkit.getDefaultToolkit().getImage("./outerSpace.jpg");
      rocketImage = Toolkit.getDefaultToolkit().getImage("./rocket.GIF");
      reset();
    }
    if (gameOver) return;
    if (rocketLife <= 0) gameOver = true;
    // missile stuff
    for (int index = 0; index < missile.length; index++) {
      if (missile[index].active) {
        if (missile[index].missileRight) missile[index].xPos += 5;
        else missile[index].xPos -= 5;

        if (missile[index].xPos >= getWidth2() || missile[index].xPos <= 0)
          missile[index].active = false;
      }
    }
    // star speeds
    for (int index = 0; index < numStars; index++) {
      starXPos[index] -= rocketXSpeed;
    }
    rocketYPos -= rocketYSpeed;
    // stop rocket at edges of screen.
    if (rocketYPos >= getHeight2()) {
      rocketYSpeed = 0;
      rocketYPos = getHeight2();
    } else if (rocketYPos <= 0) {
      rocketYSpeed = 0;
      rocketYPos = 0;
    }

    for (int index = 0; index < numStars; index++) {
      if (starXPos[index] > getWidth2()) {
        starYPos[index] = (int) (Math.random() * getHeight2());
        starXPos[index] = 0;
      } else if (starXPos[index] < 0) {
        starYPos[index] = (int) (Math.random() * getHeight2());
        starXPos[index] = getWidth2();
      }
    }
    boolean hit = false;
    for (int index = 0; index < numStars; index++) {
      if (starActive[index]) {
        if (starXPos[index] - 10 < rocketXPos
            && starXPos[index] + 10 > rocketXPos
            && starYPos[index] - 10 < rocketYPos
            && starYPos[index] + 10 > rocketYPos) {
          hit = true;
          if (starHit != index) {
            starHit = index;
            zsound = new sound("ouch.wav");
            rocketLife--;
          }
        }
      }
    }
    for (int count = 0; count < numStars; count++) {
      for (int index = 0; index < missile.length; index++) {
        if (missile[index].active && starActive[count]) {
          if (starXPos[count] - 10 < missile[index].xPos
              && starXPos[count] + 10 > missile[index].xPos
              && starYPos[count] - 10 < missile[index].yPos
              && starYPos[count] + 10 > missile[index].yPos) {
            missile[index].active = false;
            starActive[count] = false;
            score++;
            if (score > highScore) highScore = score;
          }
        }
      }
    }
    if (!hit) starHit = -1;
    if (rocketXSpeed > 0) rocketRight = true;
    else if (rocketXSpeed < 0) rocketRight = false;
  }
Exemplo n.º 29
0
  public void animate() {
    if (animateFirstTime) {
      animateFirstTime = false;
      if (xsize != getSize().width || ysize != getSize().height) {
        xsize = getSize().width;
        ysize = getSize().height;
      }
      readFile();
      outerSpaceImage = Toolkit.getDefaultToolkit().getImage("./Images/outerSpace.jpg");
      rocketImage = Toolkit.getDefaultToolkit().getImage("./Images/rocket.GIF");
      bgSound = new sound("Sound/starwars.wav");
      highscore = 0;
      reset();
    }
    if (GameOver) {
      rocketImage = Toolkit.getDefaultToolkit().getImage("./Images/rocket.GIF");
      return;
    } else if (speed > 0) {
      rocketRight = true;
      rocketImage = Toolkit.getDefaultToolkit().getImage("./Images/animrocket.GIF");
    } else if (speed < 0) {
      rocketRight = false;
      rocketImage = Toolkit.getDefaultToolkit().getImage("./Images/animRocket.GIF");
    } else rocketImage = Toolkit.getDefaultToolkit().getImage("./Images/rocket.GIF");

    if (ff) ffsize += .5;

    if (upspeed + rocketYPos > getHeight2()) {
      upspeed = 0;
      rocketYPos = getHeight2();
    } else if (upspeed + rocketYPos < 0) {
      upspeed = 0;
      rocketYPos = 0;
    } else rocketYPos += upspeed;

    for (int i = 0; i < starNum; i++) {
      star[i].setXPos(star[i].getXPos() + speed);

      if (star[i].getXPos() < 0) {
        star[i].setXPos(getWidth2());
        star[i].setYPos((int) (Math.random() * getHeight2()));
      } else if (star[i].getXPos() > getWidth2()) {
        star[i].setXPos(0);
        star[i].setYPos((int) (Math.random() * getHeight2()));
      }

      if (star[i].getLeftSide() < rocketXPos + Rocketwidth / 2
          && star[i].getRightSide() > rocketXPos - Rocketwidth / 2
          && star[i].getTop() > rocketYPos - Rocketheight / 2
          && star[i].getBottom() < rocketYPos + Rocketheight / 2) {
        if (firsttouch[i] == false) {
          zsound = new sound("Sound/ouch.wav");
          firsttouch[i] = true;
          lives--;
        }
      } else {
        firsttouch[i] = false;
      }

      if (ffsize == 2) {
        int a = rocketYPos - star[i].getYPos();
        int b = rocketXPos - star[i].getXPos();
        if (a < 0) a *= -1;
        if (b < 0) b *= -1;

        if (Math.sqrt((a * a) + (b * b)) <= ffwidth * 5 && ff) {
          if (!rocketRight) star[i].setXPos(getWidth2());
          else star[i].setXPos(0);
          star[i].setYPos((int) (Math.random() * getHeight2()));
          score++;
        }
      }
    }

    for (int i = 0; i < missle.length; i++) {
      if (missle[i].getActive()) {
        if (missle[i].getRight()) missle[i].setXPos(missle[i].getXPos() - 2);
        else missle[i].setXPos(missle[i].getXPos() + 2);

        for (int i2 = 0; i2 < starNum; i2++) {
          if (star[i2].getLeftSide() < missle[i].getRightSide()
              && star[i2].getRightSide() > missle[i].getLeftSide()
              && star[i2].getTop() > missle[i].getBottom()
              && star[i2].getBottom() < missle[i].getTop()) {
            if (!rocketRight) star[i2].setXPos(getWidth2());
            else star[i2].setXPos(0);
            star[i2].setYPos((int) (Math.random() * getHeight2()));
            missle[i].setActive(false);
            score++;
          }
        }
      }
    }

    if (lives == 0) {
      GameOver = true;
      if (score > highscore) highscore = score;
    }

    if (bgSound.donePlaying) {
      bgSound = new sound("Sound/starwars.wav");
    }

    if (ffsize >= 2) {
      ff = false;
      ffsize = 1.0;
    }

    TimeCount++;
  }
Exemplo n.º 30
0
 private float getDb(double value) {
   return (float) (Math.log(value) / Math.log(10.0) * 20.0);
 }