Мой текущий проект требует, чтобы я смешал звуковую дорожку видео с аудиофайлом, и мне удалось сделать это с помощью следующего кода:
while (mCopyAudio && !audioInternalDecoderDone && pendingInternalAudioDecoderOutputBufferIndex == -1 && (encoderOutputAudioFormat == null || muxing)) {
int decoderOutputBufferIndex = this.internalAudioDecoder.dequeueOutputBuffer(audioInternalDecoderOutputBufferInfo, TIMEOUT_USEC);
if (decoderOutputBufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
break;
}
if (decoderOutputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
audioInternalDecoderOutputBuffers = this.internalAudioDecoder.getOutputBuffers();
break;
}
if (decoderOutputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
decoderOutputAudioFormat = this.internalAudioDecoder.getOutputFormat();
iDecoderOutputChannelNum = decoderOutputAudioFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
iDecoderOutputAudioSampleRate = decoderOutputAudioFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE);
break;
}
if ((audioInternalDecoderOutputBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
//Not in indent because I couldn't fit it in the editor
this.internalAudioDecoder.releaseOutputBuffer(decoderOutputBufferIndex,
false);
break;
}
pendingInternalAudioDecoderOutputBufferIndex = decoderOutputBufferIndex;
audioDecodedFrameCount++;
break;
}
while (mCopyAudio && !audioExternalDecoderDone && pendingExternalAudioDecoderOutputBufferIndex == -1 && (encoderOutputAudioFormat == null || muxing)) {
int decoderOutputBufferIndex = this.externalAudioDecoder.dequeueOutputBuffer(audioExternalDecoderOutputBufferInfo, TIMEOUT_USEC);
if (decoderOutputBufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
break;
}
if (decoderOutputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
audioExternalDecoderOutputBuffers = this.externalAudioDecoder.getOutputBuffers();
break;
}
if (decoderOutputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
decoderOutputAudioFormat = this.externalAudioDecoder.getOutputFormat();
eDecoderOutputChannelNum = decoderOutputAudioFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
eDecoderOutputAudioSampleRate = decoderOutputAudioFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE);
break;
}
if ((audioExternalDecoderOutputBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
//Not in indent because I couldn't fit it in the editor
this.externalAudioDecoder.releaseOutputBuffer(decoderOutputBufferIndex,
false);
break;
}
pendingExternalAudioDecoderOutputBufferIndex = decoderOutputBufferIndex;
audioDecodedFrameCount++;
break;
}
while (mCopyAudio && pendingInternalAudioDecoderOutputBufferIndex != -1 && pendingExternalAudioDecoderOutputBufferIndex != -1) {
int encoderInputBufferIndex = audioEncoder.dequeueInputBuffer(TIMEOUT_USEC);
if (encoderInputBufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
break;
}
ByteBuffer encoderInputBuffer = audioEncoderInputBuffers[encoderInputBufferIndex];
int size = audioInternalDecoderOutputBufferInfo.size;
long presentationTime = audioInternalDecoderOutputBufferInfo.presentationTimeUs - musicStartUs;
if (size >= 0) {
ByteBuffer iDecoderOutputBuffer = audioInternalDecoderOutputBuffers[pendingInternalAudioDecoderOutputBufferIndex].duplicate();
ByteBuffer eDecoderOutputBuffer = audioExternalDecoderOutputBuffers[pendingExternalAudioDecoderOutputBufferIndex].duplicate();
byte[] initContents = new byte[ audioInternalDecoderOutputBufferInfo.size];
byte[] eInitContents = new byte[audioExternalDecoderOutputBufferInfo.size];
iDecoderOutputBuffer.get(initContents, 0, audioInternalDecoderOutputBufferInfo.size);
eDecoderOutputBuffer.get(eInitContents, 0, audioExternalDecoderOutputBufferInfo.size);
/*
The following is my attempt at compensating for different buffer sizes and timestamps - when the internal and external decoder buffer infos' timestampUs don't sync up with each other. This hasn't gone well.
if(audioExternalDecoderOutputBufferInfo.presentationTimeUs <= totalTime) {
if (eInitContents.length > initContents.length) {
SliceAndRemainder sar = sliceArray(eInitContents, initContents.length - remainderForNextBB.length);
Log.i("slice_and_remainder", sar.slice.length+" "+sar.remainder.length);
if(remainderForNextBB.length == initContents.length) {
eInitContents = remainderForNextBB;
remainderForNextBB = new byte[]{};
} else {
eInitContents = concatTwoArrays(remainderForNextBB, sar.slice);
remainderForNextBB = sar.remainder;
}
}else if(eInitContents.length < initContents.length) {
eInitContents = minorUpsamplingFrom44kTo48k(eInitContents);
}
}
For brevity's sake, this code is commented out, so assume the ideal condition that the timestamps in both decoders are synced up properly
*/
byte[] alteredIContents = scaleByteArrayByScalar(initContents, internalAudioGain);
byte[] alteredEContents = scaleByteArrayByScalar(eInitContents, externalAudioGain);
ByteBuffer endByteBuffer;
if(audioExternalDecoderOutputBufferInfo.presentationTimeUs <= totalTime) {
byte[] res = mixTwoByteArrays(alteredIContents, alteredEContents, alteredEContents.length);
Log.i("bytebuffer_mixed_len", res.length+"");
endByteBuffer = ByteBuffer.wrap(res);
} else {
endByteBuffer = ByteBuffer.wrap(alteredIContents);
}
iDecoderOutputBuffer.position(audioInternalDecoderOutputBufferInfo.offset);
iDecoderOutputBuffer.limit(audioInternalDecoderOutputBufferInfo.offset + size);
encoderInputBuffer.position(0);
encoderInputBuffer.put(endByteBuffer);
if((presentationTime < totalTime)) {
Log.i("presentation_time", presentationTime+" "+totalTime);
audioEncoder.queueInputBuffer(encoderInputBufferIndex, 0, size, presentationTime, audioInternalDecoderOutputBufferInfo.flags);
} else {
audioEncoder.queueInputBuffer(encoderInputBufferIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
}
}
this.internalAudioDecoder.releaseOutputBuffer(pendingInternalAudioDecoderOutputBufferIndex, false);
this.externalAudioDecoder.releaseOutputBuffer(pendingExternalAudioDecoderOutputBufferIndex, false);
pendingInternalAudioDecoderOutputBufferIndex = -1;
pendingExternalAudioDecoderOutputBufferIndex = -1;
if ((audioInternalDecoderOutputBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
lastAudioDecoderFinalFrameTimestamp += temporaryAudioDecoderTimestamp + 33333;
temporaryAudioDecoderTimestamp = 0;
audioDecoderTimestampOffset = lastAudioDecoderFinalFrameTimestamp;
audioInternalDecoderDone = true;
audioExternalDecoderDone = true;
}
break;
}
По сути, создание двух Extractor-Decoderобъединяет и объединяет их в третий блок while()
для микширования и обработки, где mixTwoByteArrays()
:
private byte[] mixTwoByteArrays(byte[] src, byte[] with, int numOfMixSamples) {
final int length = Math.min(src.length, numOfMixSamples);
byte[] result = new byte[length];
for(int i = 0; i < length; i++) {
result[i]=(byte)Math.min(0.999f,((float)src[i]+(float)with[i]));
}
return result;
}
Как указано в закомментированном коде выше, это хорошо работает для звуковых дорожек / файлов, чьивременные метки синхронизируются друг с другом.Моя проблема в тех случаях, когда они этого не делают - как в последнее время, когда звуковая дорожка имеет временные метки, кратные 26666, а аудиофайл имеет временные метки, кратные 27000 с чем-то.
Я думал об обработкезвуковые дорожки отдельно затем объединяют результат с исходной видео дорожкой, но это окажет неблагоприятное влияние на время обработки, поэтому я бы предпочел сделать это в реальном времени и использовать это решение в качестве крайней меры.
Есть ли способ сделать это в реальном времени?