java.nio.ShortBuffer#allocate ( )源码实例Demo

下面列出了java.nio.ShortBuffer#allocate ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: aion-germany   文件: BufferUtils.java
/**
 * Creates a new ShortBuffer with the same contents as the given ShortBuffer. The new ShortBuffer is seperate from the old one and changes are not reflected across. If you want to reflect changes,
 * consider using Buffer.duplicate().
 *
 * @param buf
 *            the ShortBuffer to copy
 * @return the copy
 */
public static ShortBuffer clone(ShortBuffer buf) {
	if (buf == null) {
		return null;
	}
	buf.rewind();

	ShortBuffer copy;
	if (buf.isDirect()) {
		copy = createShortBuffer(buf.limit());
	}
	else {
		copy = ShortBuffer.allocate(buf.limit());
	}
	copy.put(buf);

	return copy;
}
 
源代码2 项目: Ultraino   文件: BufferUtils.java
/**
 * Creates a new ShortBuffer with the same contents as the given
 * ShortBuffer. The new ShortBuffer is separate from the old one and changes
 * are not reflected across. If you want to reflect changes, consider using
 * Buffer.duplicate().
 *
 * @param buf
 *            the ShortBuffer to copy
 * @return the copy
 */
public static ShortBuffer clone(ShortBuffer buf) {
    if (buf == null) {
        return null;
    }
    buf.rewind();

    ShortBuffer copy;
    if (isDirect(buf)) {
        copy = createShortBuffer(buf.limit());
    } else {
        copy = ShortBuffer.allocate(buf.limit());
    }
    copy.put(buf);

    return copy;
}
 
源代码3 项目: JDA   文件: AudioConnection.java
private ByteBuffer encodeToOpus(ByteBuffer rawAudio)
{
    ShortBuffer nonEncodedBuffer = ShortBuffer.allocate(rawAudio.remaining() / 2);
    ByteBuffer encoded = ByteBuffer.allocate(4096);
    for (int i = rawAudio.position(); i < rawAudio.limit(); i += 2)
    {
        int firstByte =  (0x000000FF & rawAudio.get(i));      //Promotes to int and handles the fact that it was unsigned.
        int secondByte = (0x000000FF & rawAudio.get(i + 1));

        //Combines the 2 bytes into a short. Opus deals with unsigned shorts, not bytes.
        short toShort = (short) ((firstByte << 8) | secondByte);

        nonEncodedBuffer.put(toShort);
    }
    ((Buffer) nonEncodedBuffer).flip();

    int result = Opus.INSTANCE.opus_encode(opusEncoder, nonEncodedBuffer, OpusPacket.OPUS_FRAME_SIZE, encoded, encoded.capacity());
    if (result <= 0)
    {
        LOG.error("Received error code from opus_encode(...): {}", result);
        return null;
    }

    ((Buffer) encoded).position(0).limit(result);
    return encoded;
}
 
源代码4 项目: MikuMikuStudio   文件: BufferUtils.java
/**
 * Creates a new ShortBuffer with the same contents as the given ShortBuffer.
 * The new ShortBuffer is seperate from the old one and changes are not
 * reflected across. If you want to reflect changes, consider using
 * Buffer.duplicate().
 *
 * @param buf
 *            the ShortBuffer to copy
 * @return the copy
 */
public static ShortBuffer clone(ShortBuffer buf) {
    if (buf == null) {
        return null;
    }
    buf.rewind();

    ShortBuffer copy;
    if (buf.isDirect()) {
        copy = createShortBuffer(buf.limit());
    } else {
        copy = ShortBuffer.allocate(buf.limit());
    }
    copy.put(buf);

    return copy;
}
 
源代码5 项目: VideoAndroid   文件: Recorder.java
@Override
public void run() {
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);

    // Audio
    int bufferSize;
    ShortBuffer audioData;
    int bufferReadResult;

    bufferSize = AudioRecord.getMinBufferSize(sampleAudioRateInHz,
            AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
    mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleAudioRateInHz,
            AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);

    audioData = ShortBuffer.allocate(bufferSize);

    mAudioRecord.startRecording();

    /* ffmpeg_audio encoding loop */
    while (mRunAudioThread) {
        //获取音频数据
        bufferReadResult = mAudioRecord.read(audioData.array(), 0, audioData.capacity());
        audioData.limit(bufferReadResult);
        if (bufferReadResult > 0) {
            if(mFFmpegFrameRecorder != null && mRecording) {
                try {
                    mFFmpegFrameRecorder.recordSamples(audioData);      //写入音频数据
                } catch (FFmpegFrameRecorder.Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /* encoding finish, release recorder */
    if (mAudioRecord != null) {
        mAudioRecord.stop();
        mAudioRecord.release();
    }
}
 
源代码6 项目: ts3j   文件: OpusEncoder.java
public OpusEncoder(int sampleRate, int frameSize,
                   int channels, boolean bigEndian,
                   int maxPacketLength) {
    this.channels = channels;
    this.sampleRate = sampleRate;
    this.frameSize = frameSize;
    this.bigEndian = bigEndian;
    this.expectedByteSize = frameSize * channels * 2;

    if (!ArrayUtils.contains(OPUS_PERMITTED_FRAME_SIZES, frameSize))
        throw new IllegalArgumentException("Invalid Opus frame size: " + frameSize);

    if (!ArrayUtils.contains(OPUS_PERMITTED_SAMPLE_RATES, sampleRate))
        throw new IllegalArgumentException("Invalid Opus sample rate: " + sampleRate);

    if (!ArrayUtils.contains(OPUS_PERMITTED_CHANNEL_COUNTS, channels))
        throw new IllegalArgumentException("Invalid Opus channel count: " + channels);

    this.sourceShortBuffer = ShortBuffer.allocate(frameSize * channels);
    this.sourceByteBuffer = ByteBuffer.allocate(frameSize * channels * 2);
    this.sourceByteBuffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);

    this.targetBuffer = ByteBuffer.allocate(maxPacketLength);

    IntBuffer errorBuffer = IntBuffer.allocate(1);

    encoder = Opus.INSTANCE.opus_encoder_create(
            sampleRate,
            channels,
            Opus.OPUS_APPLICATION_AUDIO,
            errorBuffer
    );

    if (encoder == null) throw new NullPointerException("encoder");

    OpusUtil.checkError(
            "opus_encoder_create",
            errorBuffer.get()
    );
}
 
源代码7 项目: lavaplayer   文件: ChannelCountPcmAudioFilter.java
/**
 * @param inputChannels Number of input channels
 * @param outputChannels Number of output channels
 * @param downstream The next filter in line
 */
public ChannelCountPcmAudioFilter(int inputChannels, int outputChannels, UniversalPcmAudioFilter downstream) {
  this.downstream = downstream;
  this.inputChannels = inputChannels;
  this.outputChannels = outputChannels;
  this.outputBuffer = ShortBuffer.allocate(2048 * inputChannels);
  this.commonChannels = Math.min(outputChannels, inputChannels);
  this.channelsToAdd = outputChannels - commonChannels;
  this.inputSet = new short[inputChannels];
  this.splitFloatOutput = new float[outputChannels][];
  this.splitShortOutput = new short[outputChannels][];
  this.inputIndex = 0;
}
 
源代码8 项目: speech-android-sdk   文件: OggOpusEnc.java
/**
 * Encode raw audio data into Opus format then call OpusWriter to write the Ogg packet
 *
 * @param rawAudio
 * @return
 * @throws IOException
 */
public int encodeAndWrite(byte[] rawAudio) throws IOException {
    int uploadedAudioSize = 0;
    ByteArrayInputStream ios = new ByteArrayInputStream(rawAudio);

    byte[] data = new byte[SpeechConfiguration.FRAME_SIZE*2];
    int bufferSize, read;

    while((read = ios.read(data)) > 0){
        bufferSize = read;
        byte[] pcmBuffer = new byte[read];
        System.arraycopy(data, 0, pcmBuffer, 0, read);

        ShortBuffer shortBuffer = ShortBuffer.allocate(bufferSize);
        for (int i = 0; i < read; i += 2) {
            int b1 = pcmBuffer[i] & 0xff;
            int b2 = pcmBuffer[i+1] << 8;
            shortBuffer.put((short) (b1 | b2));
        }
        shortBuffer.flip();
        ByteBuffer opusBuffer = ByteBuffer.allocate(bufferSize);

        int opus_encoded = JNAOpus.INSTANCE.opus_encode(this.opusEncoder, shortBuffer, SpeechConfiguration.FRAME_SIZE, opusBuffer, bufferSize);

        opusBuffer.position(opus_encoded);
        opusBuffer.flip();

        byte[] opusData = new byte[opusBuffer.remaining()];
        opusBuffer.get(opusData, 0, opusData.length);

        if (opus_encoded > 0) {
            uploadedAudioSize += opusData.length;
            writer.writePacket(opusData, 0, opusData.length);
        }
    }

    ios.close();
    return uploadedAudioSize;
}
 
源代码9 项目: JDA   文件: Decoder.java
public short[] decodeFromOpus(AudioPacket decryptedPacket)
{
    int result;
    ShortBuffer decoded = ShortBuffer.allocate(4096);
    if (decryptedPacket == null)    //Flag for packet-loss
    {
        result = Opus.INSTANCE.opus_decode(opusDecoder, null, 0, decoded, OpusPacket.OPUS_FRAME_SIZE, 0);
        lastSeq = (char) -1;
        lastTimestamp = -1;
    }
    else
    {
        this.lastSeq = decryptedPacket.getSequence();
        this.lastTimestamp = decryptedPacket.getTimestamp();

        ByteBuffer encodedAudio = decryptedPacket.getEncodedAudio();
        int length = encodedAudio.remaining();
        int offset = encodedAudio.arrayOffset() + encodedAudio.position();
        byte[] buf = new byte[length];
        byte[] data = encodedAudio.array();
        System.arraycopy(data, offset, buf, 0, length);
        result = Opus.INSTANCE.opus_decode(opusDecoder, buf, buf.length, decoded, OpusPacket.OPUS_FRAME_SIZE, 0);
    }

    //If we get a result that is less than 0, then there was an error. Return null as a signifier.
    if (result < 0)
    {
        handleDecodeError(result);
        return null;
    }

    short[] audio = new short[result * 2];
    decoded.get(audio);
    return audio;
}
 
源代码10 项目: android-fskmodem   文件: FSKEncoder.java
protected void allocateBufferSignal() {
	if (mConfig.pcmFormat == FSKConfig.PCM_8BIT) {
		mSignalPCM8 = ByteBuffer.allocate(mConfig.sampleRate); //1 second buffer
	}
	else if (mConfig.pcmFormat == FSKConfig.PCM_16BIT) {
		mSignalPCM16 = ShortBuffer.allocate(mConfig.sampleRate); //1 second buffer
	}
}
 
源代码11 项目: succinct   文件: RandomAccessByteStreamTest.java
public void testGetShort() throws Exception {
  ShortBuffer buf = ShortBuffer.allocate(10);
  for (int i = 0; i < 10; i++) {
    buf.put((short) i);
  }
  FSDataInputStream is = TestUtils.getStream(buf);
  RandomAccessByteStream bs = new RandomAccessByteStream(is, 0, 20);
  for (int i = 0; i < 10; i++) {
    assertEquals(i, bs.getShort());
  }
}
 
源代码12 项目: succinct   文件: RandomAccessByteStreamTest.java
public void testGetShort1() throws Exception {
  ShortBuffer buf = ShortBuffer.allocate(10);
  for (int i = 0; i < 10; i++) {
    buf.put((short) i);
  }
  FSDataInputStream is = TestUtils.getStream(buf);
  RandomAccessByteStream bs = new RandomAccessByteStream(is, 0, 20);
  for (int i = 0; i < 10; i++) {
    assertEquals(i, bs.getShort(i * 2));
  }
}
 
源代码13 项目: settlers-remake   文件: ProvidedImage.java
public ShortBuffer getData() {
	ShortBuffer data = ShortBuffer.allocate(image.getWidth() * image.getHeight());
	for (int y = 0; y < image.getHeight(); y++) {
		for (int x = 0; x < image.getWidth(); x++) {
			Color color = new Color(image.getRGB(x, y));
			data.put(color.toShortColor(1));
		}
	}
	data.rewind();
	return data;
}
 
源代码14 项目: codeexamples-android   文件: BitmapPixels.java
private static ShortBuffer makeBuffer(short[] src, int n) {
    ShortBuffer dst = ShortBuffer.allocate(n*n);
    for (int i = 0; i < n; i++) {
        dst.put(src);
    }
    dst.rewind();
    return dst;
}
 
源代码15 项目: java   文件: ShortNioDataBufferTest.java
@Override
protected ShortDataBuffer allocate(long size) {
  return new ShortNioDataBuffer(ShortBuffer.allocate((int)size));
}
 
源代码16 项目: android-sdk   文件: OggOpusEnc.java
/**
 * Encode raw audio data into Opus format then call OpusWriter to write the Ogg packet.
 *
 * @param rawAudio the raw audio
 * @return the int
 * @throws IOException Signals that an I/O exception has occurred.
 */
public int encodeAndWrite(byte[] rawAudio) throws IOException {
  int uploadedAudioSize = 0;
  ByteArrayInputStream ios = new ByteArrayInputStream(rawAudio);

  byte[] data = new byte[SpeechConfiguration.FRAME_SIZE * 2];
  int bufferSize, read;

  while ((read = ios.read(data)) > 0) {
    bufferSize = read;
    byte[] pcmBuffer = new byte[read];
    System.arraycopy(data, 0, pcmBuffer, 0, read);

    ShortBuffer shortBuffer = ShortBuffer.allocate(bufferSize);
    for (int i = 0; i < read; i += 2) {
      int b1 = pcmBuffer[i] & 0xff;
      int b2 = pcmBuffer[i + 1] << 8;
      shortBuffer.put((short) (b1 | b2));
    }
    shortBuffer.flip();
    ByteBuffer opusBuffer = ByteBuffer.allocate(bufferSize);

    int opus_encoded = JNAOpus.INSTANCE.opus_encode(this.opusEncoder, shortBuffer, SpeechConfiguration.FRAME_SIZE,
            opusBuffer, bufferSize);

    opusBuffer.position(opus_encoded);
    opusBuffer.flip();

    byte[] opusData = new byte[opusBuffer.remaining()];
    opusBuffer.get(opusData, 0, opusData.length);

    if (opus_encoded > 0) {
      uploadedAudioSize += opusData.length;
      // System.out.println("This is where I'd write some data. " + uploadedAudioSize + " to be specific.");
      writer.writePacket(opusData, 0, opusData.length);
    }
  }

  ios.close();

  return uploadedAudioSize;
}
 
源代码17 项目: android-fskmodem   文件: FSKDecoder.java
protected void allocateBufferSignal() {
	mSignal = ShortBuffer.allocate(mSignalBufferSize);
}
 
源代码18 项目: android-fskmodem   文件: FSKDecoder.java
protected void allocateBufferFrame() {
	mFrame = ShortBuffer.allocate(mConfig.samplesPerBit); // one frame contains one bit
}
 
源代码19 项目: settlers-remake   文件: NullImage.java
private NullImage() {
	super(ShortBuffer.allocate(1), 1, 1, 0, 0, "placeholder/null");
}
 
源代码20 项目: settlers-remake   文件: SettlerImage.java
private void generateUData() {
	toffsetX = offsetX;
	toffsetY = offsetY;

	int tx = offsetX+width;
	int ty = offsetY+height;

	if(torso != null) {
		if(torso.offsetX < toffsetX) toffsetX = torso.offsetX;
		if(torso.offsetY < toffsetY) toffsetY = torso.offsetY;
		if(torso.offsetX+torso.width > tx) tx = torso.offsetX+torso.width;
		if(torso.offsetY+torso.height > ty) ty = torso.offsetY+torso.height;
	}

	if(shadow != null) {
		if(shadow.offsetX < toffsetX) toffsetX = shadow.offsetX;
		if(shadow.offsetY < toffsetY) toffsetY = shadow.offsetY;
		if(shadow.offsetX+shadow.width > tx) tx = shadow.offsetX+shadow.width;
		if(shadow.offsetY+shadow.height > ty) ty = shadow.offsetY+shadow.height;
	}

	twidth = tx-toffsetX;
	theight = ty-toffsetY;

	tdata = ShortBuffer.allocate(twidth * theight);

	short[] temp = new short[0];

	if(shadow != null) {
		int hoffX = shadow.offsetX-toffsetX;
		int hoffY = shadow.offsetY-toffsetY;

		if(temp.length < shadow.width) temp = new short[shadow.width];

		for(int y = 0;y != shadow.height;y++) {
			shadow.data.position(y*shadow.width);
			shadow.data.get(temp, 0, shadow.width);

			for(int x = 0;x != shadow.width;x++) {
				if(temp[x] == 0) continue;
				tdata.put((y+hoffY)*twidth+hoffX+x, (short)((temp[x]&0xF)<<8)); // move alpha to green
			}
		}
	}

	if(torso != null) {
		int toffX = torso.offsetX-toffsetX;
		int toffY = torso.offsetY-toffsetY;

		if(temp.length < torso.width) temp = new short[torso.width];

		for(int y = 0;y != torso.height;y++) {
			torso.data.position(y*torso.width);
			torso.data.get(temp, 0, torso.width);

			for(int x = 0;x != torso.width;x++) {
				if(temp[x] == 0) continue;
				tdata.put((y+toffY)*twidth+toffX+x, (short) ((temp[x]&0xF0)|0xF000)); // strip out everything except blue channel and set full red channel
			}
		}
	}

	int soffX = offsetX-toffsetX;
	int soffY = offsetY-toffsetY;

	if(temp.length < width) temp = new short[width];

	for(int y = 0;y != height;y++) {
		data.position(y*width);
		data.get(temp, 0, width);

		for(int x = 0;x != width;x++) {
			if(temp[x] != 0) tdata.put((y+soffY)*twidth+soffX+x, temp[x]);
		}
	}
}