下面列出了java.nio.ShortBuffer#allocate ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
/**
* 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;
}
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;
}
/**
* 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;
}
@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();
}
}
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()
);
}
/**
* @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;
}
/**
* 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;
}
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;
}
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
}
}
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());
}
}
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));
}
}
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;
}
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;
}
@Override
protected ShortDataBuffer allocate(long size) {
return new ShortNioDataBuffer(ShortBuffer.allocate((int)size));
}
/**
* 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;
}
protected void allocateBufferSignal() {
mSignal = ShortBuffer.allocate(mSignalBufferSize);
}
protected void allocateBufferFrame() {
mFrame = ShortBuffer.allocate(mConfig.samplesPerBit); // one frame contains one bit
}
private NullImage() {
super(ShortBuffer.allocate(1), 1, 1, 0, 0, "placeholder/null");
}
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]);
}
}
}