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(); } }
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(); } }
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(); }
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; }
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 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(); }
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); }
/** 列に周波数とバイト列の長さ指定で形を書き込む */ 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); }
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(); // 終了まで }
/** バイト列に周波数、ベロシティ指定で波形書き込む */ 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); }
@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; } }
/** * Write one sample (between -1.0 and +1.0) to standard audio. If the sample is outside the range, * it will be clipped. */ public static void play(double in) { // clip if outside [-1, +1] if (in < -1.0) in = -1.0; if (in > +1.0) in = +1.0; // convert to bytes short s = (short) (MAX_16_BIT * in); buffer[bufferSize++] = (byte) s; buffer[bufferSize++] = (byte) (s >> 8); // little Endian // send to sound card if buffer is full if (bufferSize >= buffer.length) { line.write(buffer, 0, buffer.length); bufferSize = 0; } }
/** * this will try to write all the indicated data whitout ever giving up... Either all the data is * written or it will loop for ever. * * @param data * @param ofs * @param len */ private void writeData(byte[] data, int ofs, int len) { int count = 0; int written = 0; while (written < len) { written += sdl.write(data, ofs + written, len - written); // take a litle break if we couldn't write everything in 100 // tries... count++; if (count >= 100) { try { Thread.sleep(10); } catch (InterruptedException e) { } count = 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); } }
public void sync() { final int scrollx = m[SX]; final int scrolly = m[SY]; java.util.Arrays.fill(p, m[CL]); drawGrid(false, scrollx, scrolly); for (int sprite = 0; sprite < 1024; sprite += 4) { final int status = m[m[SP] + sprite]; final int tile = m[m[SP] + sprite + 1]; final int px = m[m[SP] + sprite + 2]; final int py = m[m[SP] + sprite + 3]; drawSprite(tile, status, px - scrollx, py - scrolly); } drawGrid(true, scrollx, scrolly); if (soundLine != null && apointer > 0) { soundLine.write(abuffer, 0, apointer); apointer = 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(); } }
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(); } }
/** バイト列をlineに出力するラッパ */ public void myWrite(byte[] b, int n, int length) { line.write(b, n, length); }
/** Write data to the source data line. */ public void run() { byte[] buffer = null; boolean useStream = (ais != null); if (useStream) { buffer = new byte[BUFFER_SIZE]; } else { buffer = audioData; } while (wantedState != STATE_STOPPING) { // try { if (wantedState == STATE_WAITING) { // wait for 5 seconds - maybe the clip is to be played again if (DEBUG || Printer.debug) Printer.debug("DataPusher.run(): waiting 5 seconds"); try { synchronized (this) { threadState = STATE_WAITING; wantedState = STATE_STOPPING; wait(AUTO_CLOSE_TIME); } } catch (InterruptedException ie) { } if (DEBUG || Printer.debug) Printer.debug("DataPusher.run(): waiting finished"); continue; } if (newPos >= 0) { pos = newPos; newPos = -1; } threadState = STATE_PLAYING; int toWrite = BUFFER_SIZE; if (useStream) { try { pos = 0; // always write from beginning of buffer // don't use read(byte[]), because some streams // may not override that method toWrite = ais.read(buffer, 0, buffer.length); } catch (java.io.IOException ioe) { // end of stream toWrite = -1; } } else { if (toWrite > audioDataByteLength - pos) { toWrite = audioDataByteLength - pos; } if (toWrite == 0) { toWrite = -1; // end of "stream" } } if (toWrite < 0) { if (DEBUG || Printer.debug) Printer.debug("DataPusher.run(): Found end of stream"); if (!useStream && looping) { if (DEBUG || Printer.debug) Printer.debug("DataPusher.run(): setting pos back to 0"); pos = 0; continue; } if (DEBUG || Printer.debug) Printer.debug("DataPusher.run(): calling drain()"); wantedState = STATE_WAITING; source.drain(); continue; } if (DEBUG || Printer.debug) Printer.debug("> DataPusher.run(): Writing " + toWrite + " bytes"); int bytesWritten = source.write(buffer, pos, toWrite); pos += bytesWritten; if (DEBUG || Printer.debug) Printer.debug("< DataPusher.run(): Wrote " + bytesWritten + " bytes"); } threadState = STATE_STOPPING; if (DEBUG || Printer.debug) Printer.debug("DataPusher: closing device"); if (Printer.trace) Printer.trace("DataPusher: source.flush()"); source.flush(); if (DEBUG || Printer.trace) Printer.trace("DataPusher: source.stop()"); source.stop(); if (DEBUG || Printer.trace) Printer.trace("DataPusher: source.flush()"); source.flush(); if (DEBUG || Printer.trace) Printer.trace("DataPusher: source.close()"); source.close(); threadState = STATE_STOPPED; synchronized (this) { pushThread = null; notifyAll(); } if (DEBUG || Printer.debug) Printer.debug("DataPusher:end of thread"); }