Java Code Examples for android.media.MediaFormat#setString()

The following examples show how to use android.media.MediaFormat#setString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MediaFormatFactory.java    From AlexaAndroid with GNU General Public License v2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static MediaFormat createMediaFormat(Type type, int sampleRate) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        MediaFormat format = new MediaFormat();
        // TODO: this causes a crash in MediaCodec.configure
        //format.setString(MediaFormat.KEY_FRAME_RATE, null);
        format.setInteger(MediaFormat.KEY_SAMPLE_RATE, sampleRate);
        format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
        if (type == Type.AAC) {
            format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm");
            format.setInteger(MediaFormat.KEY_AAC_PROFILE, 2); // TODO: or 39?
            format.setInteger(MediaFormat.KEY_BIT_RATE, 64000);
        } else if (type == Type.FLAC) {
            //format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_FLAC); // API=21
            format.setString(MediaFormat.KEY_MIME, "audio/flac");
            format.setInteger(MediaFormat.KEY_BIT_RATE, 64000);
            //TODO: use another bit rate, does not seem to have effect always
            //format.setInteger(MediaFormat.KEY_BIT_RATE, 128000);
        } else {
            format.setString(MediaFormat.KEY_MIME, "audio/amr-wb");
            format.setInteger(MediaFormat.KEY_BIT_RATE, 23050);
        }
        return format;
    }
    return null;
}
 
Example 2
Source File: MediaCodecAudioRenderer.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the framework {@link MediaFormat} that can be used to configure a {@link MediaCodec}
 * for decoding the given {@link Format} for playback.
 *
 * @param format The format of the media.
 * @param codecMimeType The MIME type handled by the codec.
 * @param codecMaxInputSize The maximum input size supported by the codec.
 * @param codecOperatingRate The codec operating rate, or {@link #CODEC_OPERATING_RATE_UNSET} if
 *     no codec operating rate should be set.
 * @return The framework media format.
 */
@SuppressLint("InlinedApi")
protected MediaFormat getMediaFormat(
    Format format, String codecMimeType, int codecMaxInputSize, float codecOperatingRate) {
  MediaFormat mediaFormat = new MediaFormat();
  // Set format parameters that should always be set.
  mediaFormat.setString(MediaFormat.KEY_MIME, codecMimeType);
  mediaFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, format.channelCount);
  mediaFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, format.sampleRate);
  MediaFormatUtil.setCsdBuffers(mediaFormat, format.initializationData);
  // Set codec max values.
  MediaFormatUtil.maybeSetInteger(mediaFormat, MediaFormat.KEY_MAX_INPUT_SIZE, codecMaxInputSize);
  // Set codec configuration values.
  if (Util.SDK_INT >= 23) {
    mediaFormat.setInteger(MediaFormat.KEY_PRIORITY, 0 /* realtime priority */);
    if (codecOperatingRate != CODEC_OPERATING_RATE_UNSET && !deviceDoesntSupportOperatingRate()) {
      mediaFormat.setFloat(MediaFormat.KEY_OPERATING_RATE, codecOperatingRate);
    }
  }
  if (Util.SDK_INT <= 28 && MimeTypes.AUDIO_AC4.equals(format.sampleMimeType)) {
    // On some older builds, the AC-4 decoder expects to receive samples formatted as raw frames
    // not sync frames. Set a format key to override this.
    mediaFormat.setInteger("ac4-is-sync", 1);
  }
  return mediaFormat;
}
 
Example 3
Source File: Format3GP.java    From Android-Audio-Recorder with Apache License 2.0 6 votes vote down vote up
public Format3GP(EncoderInfo info, File out) {
        MediaFormat format = new MediaFormat();

        // for high bitrate AMR_WB
        {
//            final int kBitRates[] = {6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 23850};

//            format.setString(MediaFormat.KEY_MIME, "audio/amr-wb");
//            format.setInteger(MediaFormat.KEY_SAMPLE_RATE, info.sampleRate);
//            format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, info.channels);
//            format.setInteger(MediaFormat.KEY_BIT_RATE, 23850); // set maximum
        }

        // for low bitrate, AMR_NB
        {
//            final int kBitRates[] = {4750, 5150, 5900, 6700, 7400, 7950, 10200, 12200};

            format.setString(MediaFormat.KEY_MIME, "audio/3gpp");
            format.setInteger(MediaFormat.KEY_SAMPLE_RATE, info.sampleRate); // 8000 only supported
            format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, info.channels);
            format.setInteger(MediaFormat.KEY_BIT_RATE, 12200); // set maximum
        }

        create(info, format, out);
    }
 
Example 4
Source File: AACHelper.java    From CameraV with GNU General Public License v3.0 6 votes vote down vote up
public boolean setDecoder(int sampleRate, int channels, int bitRate) throws Exception
{
    decoder = MediaCodec.createDecoderByType("audio/mp4a-latm");
    MediaFormat format = new MediaFormat();
    format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm");
    format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, channels);
    format.setInteger(MediaFormat.KEY_SAMPLE_RATE, sampleRate);
    format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate * 1024);//AAC-HE 64kbps
    format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectHE);

    decoder.configure(format, null, null, 0);
    
    setPlayer(sampleRate);

    return true;
}
 
Example 5
Source File: AudioCodec.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private MediaCodec createMediaCodec(int bufferSize) throws IOException {
    MediaCodec mediaCodec = MediaCodec.createEncoderByType("audio/mp4a-latm");
    MediaFormat mediaFormat = new MediaFormat();

    mediaFormat.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm");
    mediaFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, SAMPLE_RATE);
    mediaFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, CHANNELS);
    mediaFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, bufferSize);
    mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE);
    mediaFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);

    try {
        mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
    } catch (Exception e) {
        Log.w(TAG, e);
        mediaCodec.release();
        throw new IOException(e);
    }

    return mediaCodec;
}
 
Example 6
Source File: MediaCodecAudioRenderer.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the framework {@link MediaFormat} that can be used to configure a {@link MediaCodec}
 * for decoding the given {@link Format} for playback.
 *
 * @param format The format of the media.
 * @param codecMimeType The MIME type handled by the codec.
 * @param codecMaxInputSize The maximum input size supported by the codec.
 * @param codecOperatingRate The codec operating rate, or {@link #CODEC_OPERATING_RATE_UNSET} if
 *     no codec operating rate should be set.
 * @return The framework media format.
 */
@SuppressLint("InlinedApi")
protected MediaFormat getMediaFormat(
    Format format, String codecMimeType, int codecMaxInputSize, float codecOperatingRate) {
  MediaFormat mediaFormat = new MediaFormat();
  // Set format parameters that should always be set.
  mediaFormat.setString(MediaFormat.KEY_MIME, codecMimeType);
  mediaFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, format.channelCount);
  mediaFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, format.sampleRate);
  MediaFormatUtil.setCsdBuffers(mediaFormat, format.initializationData);
  // Set codec max values.
  MediaFormatUtil.maybeSetInteger(mediaFormat, MediaFormat.KEY_MAX_INPUT_SIZE, codecMaxInputSize);
  // Set codec configuration values.
  if (Util.SDK_INT >= 23) {
    mediaFormat.setInteger(MediaFormat.KEY_PRIORITY, 0 /* realtime priority */);
    if (codecOperatingRate != CODEC_OPERATING_RATE_UNSET) {
      mediaFormat.setFloat(MediaFormat.KEY_OPERATING_RATE, codecOperatingRate);
    }
  }
  return mediaFormat;
}
 
Example 7
Source File: AudioEncoder.java    From LiveMultimedia with Apache License 2.0 5 votes vote down vote up
public synchronized void createAudioFormat() {
    if (Thread.currentThread().isInterrupted()) {
        release();
    }
    mAudioFormat  = new MediaFormat();
    mAudioFormat.setString(MediaFormat.KEY_MIME, AUDIO_MIME_TYPE);
    mAudioFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
    mAudioFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, 44100);
    mAudioFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
    mAudioFormat.setInteger(MediaFormat.KEY_BIT_RATE, 128000);
    mAudioFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 16384);
}
 
Example 8
Source File: FormatM4A.java    From Android-Audio-Recorder with Apache License 2.0 5 votes vote down vote up
public FormatM4A(EncoderInfo info, File out) {
    MediaFormat format = new MediaFormat();
    format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm");
    format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectHE);
    format.setInteger(MediaFormat.KEY_SAMPLE_RATE, info.sampleRate);
    format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, info.channels);
    format.setInteger(MediaFormat.KEY_BIT_RATE, 64000);

    create(info, format, out);
}
 
Example 9
Source File: AudioWriter.java    From ssj with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Configures the encoder
 */
private void prepareEncoder() throws IOException
{
    //set format properties
    MediaFormat audioFormat = new MediaFormat();
    audioFormat.setString(MediaFormat.KEY_MIME, options.mimeType.get());
    audioFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
    audioFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, iSampleRate);
    audioFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, iSampleDimension);
    audioFormat.setInteger(MediaFormat.KEY_BIT_RATE, iSampleNumber);
    audioFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, aByShuffle.length);
    //prepare encoder
    super.prepareEncoder(audioFormat, options.mimeType.get(), file.getPath());
}
 
Example 10
Source File: MediaCodecVideoRenderer.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the framework {@link MediaFormat} that should be used to configure the decoder.
 *
 * @param format The format of media.
 * @param codecMaxValues Codec max values that should be used when configuring the decoder.
 * @param codecOperatingRate The codec operating rate, or {@link #CODEC_OPERATING_RATE_UNSET} if
 *     no codec operating rate should be set.
 * @param deviceNeedsAutoFrcWorkaround Whether the device is known to enable frame-rate conversion
 *     logic that negatively impacts ExoPlayer.
 * @param tunnelingAudioSessionId The audio session id to use for tunneling, or {@link
 *     C#AUDIO_SESSION_ID_UNSET} if tunneling should not be enabled.
 * @return The framework {@link MediaFormat} that should be used to configure the decoder.
 */
@SuppressLint("InlinedApi")
protected MediaFormat getMediaFormat(
    Format format,
    CodecMaxValues codecMaxValues,
    float codecOperatingRate,
    boolean deviceNeedsAutoFrcWorkaround,
    int tunnelingAudioSessionId) {
  MediaFormat mediaFormat = new MediaFormat();
  // Set format parameters that should always be set.
  mediaFormat.setString(MediaFormat.KEY_MIME, format.sampleMimeType);
  mediaFormat.setInteger(MediaFormat.KEY_WIDTH, format.width);
  mediaFormat.setInteger(MediaFormat.KEY_HEIGHT, format.height);
  MediaFormatUtil.setCsdBuffers(mediaFormat, format.initializationData);
  // Set format parameters that may be unset.
  MediaFormatUtil.maybeSetFloat(mediaFormat, MediaFormat.KEY_FRAME_RATE, format.frameRate);
  MediaFormatUtil.maybeSetInteger(mediaFormat, MediaFormat.KEY_ROTATION, format.rotationDegrees);
  MediaFormatUtil.maybeSetColorInfo(mediaFormat, format.colorInfo);
  // Set codec max values.
  mediaFormat.setInteger(MediaFormat.KEY_MAX_WIDTH, codecMaxValues.width);
  mediaFormat.setInteger(MediaFormat.KEY_MAX_HEIGHT, codecMaxValues.height);
  MediaFormatUtil.maybeSetInteger(
      mediaFormat, MediaFormat.KEY_MAX_INPUT_SIZE, codecMaxValues.inputSize);
  // Set codec configuration values.
  if (Util.SDK_INT >= 23) {
    mediaFormat.setInteger(MediaFormat.KEY_PRIORITY, 0 /* realtime priority */);
    if (codecOperatingRate != CODEC_OPERATING_RATE_UNSET) {
      mediaFormat.setFloat(MediaFormat.KEY_OPERATING_RATE, codecOperatingRate);
    }
  }
  if (deviceNeedsAutoFrcWorkaround) {
    mediaFormat.setInteger("auto-frc", 0);
  }
  if (tunnelingAudioSessionId != C.AUDIO_SESSION_ID_UNSET) {
    configureTunnelingV21(mediaFormat, tunnelingAudioSessionId);
  }
  return mediaFormat;
}
 
Example 11
Source File: MediaFormatFactory.java    From speechutils with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static MediaFormat createMediaFormat(String mime, int sampleRate) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        MediaFormat format = new MediaFormat();
        // TODO: this causes a crash in MediaCodec.configure
        //format.setString(MediaFormat.KEY_FRAME_RATE, null);
        format.setInteger(MediaFormat.KEY_SAMPLE_RATE, sampleRate);
        format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
        format.setString(MediaFormat.KEY_MIME, mime);
        if ("audio/mp4a-latm".equals(mime)) {
            format.setInteger(MediaFormat.KEY_AAC_PROFILE, 2); // TODO: or 39?
            format.setInteger(MediaFormat.KEY_BIT_RATE, 64000);
        } else if ("audio/flac".equals(mime)) {
            //format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_FLAC); // API=21
            format.setInteger(MediaFormat.KEY_BIT_RATE, 64000);
            //TODO: use another bit rate, does not seem to have effect always
            //format.setInteger(MediaFormat.KEY_BIT_RATE, 128000);
            // TODO: experiment with 0 (fastest/least) to 8 (slowest/most)
            //format.setInteger(MediaFormat.KEY_FLAC_COMPRESSION_LEVEL, 0);
        } else if ("audio/opus".equals(mime)) {
            //format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_OPUS); // API=21
            format.setInteger(MediaFormat.KEY_BIT_RATE, 64000);
        } else {
            // TODO: assuming: "audio/amr-wb"
            format.setInteger(MediaFormat.KEY_BIT_RATE, 23050);
        }
        return format;
    }
    return null;
}
 
Example 12
Source File: StreamingAudioEncoder.java    From live-transcribe-speech-engine with Apache License 2.0 5 votes vote down vote up
/** Configure the codec at a specified bitrate for a fixed sample block size. */
private static MediaFormat getMediaFormat(CodecAndBitrate codecAndBitrate, int sampleRateHz) {
  MediaFormat format = new MediaFormat();
  CodecType codecType = lookupCodecType(codecAndBitrate);
  format.setString(MediaFormat.KEY_MIME, getMime(codecType));
  format.setInteger(MediaFormat.KEY_SAMPLE_RATE, sampleRateHz);
  format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
  format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, BYTES_PER_SAMPLE * CHUNK_SIZE_SAMPLES);
  if (codecType != CodecType.FLAC) {
    // FLAC is lossless, we can't request a bitrate.
    format.setInteger(MediaFormat.KEY_BIT_RATE, codecAndBitrate.getNumber());
  }
  return format;
}
 
Example 13
Source File: TranscoderUtilsShould.java    From LiTr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);

    targetVideoFormat = new MediaFormat();
    targetVideoFormat.setString(MediaFormat.KEY_MIME, "video/avc");
    targetVideoFormat.setInteger(MediaFormat.KEY_WIDTH, 1280);
    targetVideoFormat.setInteger(MediaFormat.KEY_HEIGHT, 720);
    targetVideoFormat.setInteger(MediaFormat.KEY_BIT_RATE, 3300000);
    targetVideoFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);

    when(videoMediaFormat.containsKey(MediaFormat.KEY_MIME)).thenReturn(true);
    when(videoMediaFormat.getString(MediaFormat.KEY_MIME)).thenReturn("video/avc");
    when(videoMediaFormat.containsKey(MediaFormat.KEY_BIT_RATE)).thenReturn(true);
    when(videoMediaFormat.getInteger(MediaFormat.KEY_BIT_RATE)).thenReturn(VIDEO_BIT_RATE);
    when(videoMediaFormat.containsKey(MediaFormat.KEY_DURATION)).thenReturn(true);
    when(videoMediaFormat.getLong(MediaFormat.KEY_DURATION)).thenReturn(DURATION_US);
    when(videoMediaFormat.getInteger(MediaFormat.KEY_WIDTH)).thenReturn(VIDEO_WIDTH);
    when(videoMediaFormat.getInteger(MediaFormat.KEY_HEIGHT)).thenReturn(VIDEO_HEIGHT);

    when(audioMediaFormat.containsKey(MediaFormat.KEY_MIME)).thenReturn(true);
    when(audioMediaFormat.getString(MediaFormat.KEY_MIME)).thenReturn("audio/mp4a-latm");
    when(audioMediaFormat.containsKey(MediaFormat.KEY_DURATION)).thenReturn(true);
    when(audioMediaFormat.getLong(MediaFormat.KEY_DURATION)).thenReturn(DURATION_US);

    when(miscMediaFormat.containsKey(MediaFormat.KEY_MIME)).thenReturn(true);
    when(miscMediaFormat.getString(MediaFormat.KEY_MIME)).thenReturn("text/vnd.dvb.subtitle");

    when(mediaSource.getTrackFormat(0)).thenReturn(videoMediaFormat);
    when(mediaSource.getTrackFormat(1)).thenReturn(audioMediaFormat);
}
 
Example 14
Source File: AACDecoder.java    From AndroidScreenShare with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化解码器
 *
 * @return 初始化失败返回false,成功返回true
 */
public boolean prepare() {

    try {
        //需要解码数据的类型
        String mine = "audio/mp4a-latm";
        //初始化解码器
        mDecoder = MediaCodec.createDecoderByType(mine);
        //MediaFormat用于描述音视频数据的相关参数
        MediaFormat mediaFormat = new MediaFormat();
        //数据类型
        mediaFormat.setString(MediaFormat.KEY_MIME, mine);
        //声道个数
        mediaFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, channelCount);
        //采样率
        mediaFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, sampleRate);
        //比特率
        mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
        //用来标记AAC是否有adts头,1->有
        mediaFormat.setInteger(MediaFormat.KEY_IS_ADTS, 1);
        //用来标记aac的类型
        mediaFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
        //ByteBuffer key(暂时不了解该参数的含义,但必须设置)
        byte[] data = new byte[]{(byte) 0x11, (byte) 0x90};
        ByteBuffer csd_0 = ByteBuffer.wrap(data);
        mediaFormat.setByteBuffer("csd-0", csd_0);
        //解码器配置
        mDecoder.configure(mediaFormat, null, null, 0);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    if (mDecoder == null) {
        return false;
    }
    mDecoder.start();
    return true;
}
 
Example 15
Source File: Transcode.java    From cloudinary_android with MIT License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private MediaFormat createTargetVideoFormat(int width, int height, int bitrate, int keyFrameInterval, int frameRate) {
    MediaFormat targetVideoFormat = new MediaFormat();
    targetVideoFormat.setString(MediaFormat.KEY_MIME, "video/avc");
    targetVideoFormat.setInteger(MediaFormat.KEY_WIDTH, width);
    targetVideoFormat.setInteger(MediaFormat.KEY_HEIGHT, height);
    targetVideoFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);
    targetVideoFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, keyFrameInterval);
    targetVideoFormat.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);
    targetVideoFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);

    return targetVideoFormat;
}
 
Example 16
Source File: AACHelper.java    From CameraV with GNU General Public License v3.0 5 votes vote down vote up
public boolean setEncoder(int sampleRate, int channels, int bitRate) throws Exception
{
    encoder = MediaCodec.createEncoderByType("audio/mp4a-latm");
    MediaFormat format = new MediaFormat();
    format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm");
    format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, channels);
    format.setInteger(MediaFormat.KEY_SAMPLE_RATE, sampleRate);
    format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate * 1024);//AAC-HE 64kbps
    format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectHE);
    encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
    
    initAudioRecord(sampleRate);
    
    return true;
}
 
Example 17
Source File: AACStream.java    From spydroid-ipcamera with GNU General Public License v3.0 4 votes vote down vote up
@Override
@SuppressLint({ "InlinedApi", "NewApi" })
protected void encodeWithMediaCodec() throws IOException {

	final int bufferSize = AudioRecord.getMinBufferSize(mQuality.samplingRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)*2;

	((AACLATMPacketizer)mPacketizer).setSamplingRate(mQuality.samplingRate);

	mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, mQuality.samplingRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
	mMediaCodec = MediaCodec.createEncoderByType("audio/mp4a-latm");
	MediaFormat format = new MediaFormat();
	format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm");
	format.setInteger(MediaFormat.KEY_BIT_RATE, mQuality.bitRate);
	format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
	format.setInteger(MediaFormat.KEY_SAMPLE_RATE, mQuality.samplingRate);
	format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
	format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, bufferSize);
	mMediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
	mAudioRecord.startRecording();
	mMediaCodec.start();

	final MediaCodecInputStream inputStream = new MediaCodecInputStream(mMediaCodec);
	final ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();

	mThread = new Thread(new Runnable() {
		@Override
		public void run() {
			int len = 0, bufferIndex = 0;
			try {
				while (!Thread.interrupted()) {
					bufferIndex = mMediaCodec.dequeueInputBuffer(10000);
					if (bufferIndex>=0) {
						inputBuffers[bufferIndex].clear();
						len = mAudioRecord.read(inputBuffers[bufferIndex], bufferSize);
						if (len ==  AudioRecord.ERROR_INVALID_OPERATION || len == AudioRecord.ERROR_BAD_VALUE) {
							Log.e(TAG,"An error occured with the AudioRecord API !");
						} else {
							//Log.v(TAG,"Pushing raw audio to the decoder: len="+len+" bs: "+inputBuffers[bufferIndex].capacity());
							mMediaCodec.queueInputBuffer(bufferIndex, 0, len, System.nanoTime()/1000, 0);
						}
					}
				}
			} catch (RuntimeException e) {
				e.printStackTrace();
			}
		}
	});

	mThread.start();

	// The packetizer encapsulates this stream in an RTP stream and send it over the network
	mPacketizer.setDestination(mDestination, mRtpPort, mRtcpPort);
	mPacketizer.setInputStream(inputStream);
	mPacketizer.start();

	mStreaming = true;

}
 
Example 18
Source File: AudioEncoder.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
@Override
protected void prepare() throws IOException {
    AudioQuality audioQuality = getAudioQuality();

    String mimeType = audioQuality.getMimeType();

    List<MediaCodecInfo> infoList = getMediaCodecInfo(mimeType);
    if (infoList.isEmpty()) {
        throw new IOException(mimeType + " not supported.");
    }

    MediaFormat format = MediaFormat.createAudioFormat(audioQuality.getMimeType(),
            audioQuality.getSamplingRate(), audioQuality.getChannelCount());
    format.setString(MediaFormat.KEY_MIME, audioQuality.getMimeType());
    format.setInteger(MediaFormat.KEY_SAMPLE_RATE, audioQuality.getSamplingRate());
    format.setInteger(MediaFormat.KEY_BIT_RATE, audioQuality.getBitRate());
    format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, audioQuality.getChannelCount());
    format.setInteger(MediaFormat.KEY_CHANNEL_MASK, audioQuality.getChannel());
    format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
    if (audioQuality.getMaxInputSize() > 0) {
        format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, audioQuality.getMaxInputSize());
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // 0: realtime priority
        // 1: non-realtime priority (best effort).
        format.setInteger(MediaFormat.KEY_PRIORITY, 0x00);
    }

    if (DEBUG) {
        Log.d(TAG, "List of MediaCodeInfo supported by MediaCodec.");
        for (MediaCodecInfo info : infoList) {
            Log.d(TAG, "  " + info.getName());
        }
        Log.i(TAG, "---");
        Log.i(TAG, "MIME_TYPE: " + audioQuality.getMimeType());
        Log.i(TAG, "SAMPLE_RATE: " + audioQuality.getSamplingRate());
        Log.i(TAG, "CHANNEL: " + audioQuality.getChannelCount());
        Log.i(TAG, "FORMAT: " + audioQuality.getFormat());
        Log.i(TAG, "BIT_RATE: " + audioQuality.getBitRate());
        Log.i(TAG, "---");
    }

    mMediaCodec = MediaCodec.createEncoderByType(audioQuality.getMimeType());
    mMediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
}
 
Example 19
Source File: DefaultStrategy.java    From GIFCompressor with Apache License 2.0 4 votes vote down vote up
@Override
public void createOutputFormat(@NonNull List<MediaFormat> inputFormats,
                               @NonNull MediaFormat outputFormat) {

    // Compute output size in rotation=0 reference.
    ExactSize inSize = getBestInputSize(inputFormats);
    int inWidth = inSize.getWidth();
    int inHeight = inSize.getHeight();
    LOG.i("Input width&height: " + inWidth + "x" + inHeight);
    Size outSize;
    try {
        outSize = options.resizer.getOutputSize(inSize);
    } catch (Exception e) {
        throw new RuntimeException("Resizer error:", e);
    }
    int outWidth, outHeight;
    if (outSize instanceof ExactSize) {
        outWidth = ((ExactSize) outSize).getWidth();
        outHeight = ((ExactSize) outSize).getHeight();
    } else if (inWidth >= inHeight) {
        outWidth = outSize.getMajor();
        outHeight = outSize.getMinor();
    } else {
        outWidth = outSize.getMinor();
        outHeight = outSize.getMajor();
    }
    LOG.i("Output width&height: " + outWidth + "x" + outHeight);

    // Compute output frame rate. It can't be bigger than input frame rate.
    int outFrameRate;
    int inputFrameRate = getMinFrameRate(inputFormats);
    if (inputFrameRate > 0) {
        outFrameRate = Math.min(inputFrameRate, options.targetFrameRate);
    } else {
        outFrameRate = options.targetFrameRate;
    }

    // Create the actual format.
    outputFormat.setString(MediaFormat.KEY_MIME, options.targetMimeType);
    outputFormat.setInteger(MediaFormat.KEY_WIDTH, outWidth);
    outputFormat.setInteger(MediaFormat.KEY_HEIGHT, outHeight);
    outputFormat.setInteger(MediaFormatConstants.KEY_ROTATION_DEGREES, 0);
    outputFormat.setInteger(MediaFormat.KEY_FRAME_RATE, outFrameRate);
    if (Build.VERSION.SDK_INT >= 25) {
        outputFormat.setFloat(MediaFormat.KEY_I_FRAME_INTERVAL, options.targetKeyFrameInterval);
    } else {
        outputFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, (int) Math.ceil(options.targetKeyFrameInterval));
    }
    outputFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
    int outBitRate = (int) (options.targetBitRate == BITRATE_UNKNOWN ?
            estimateBitRate(outWidth, outHeight, outFrameRate) : options.targetBitRate);
    outputFormat.setInteger(MediaFormat.KEY_BIT_RATE, outBitRate);
}
 
Example 20
Source File: MediaFormatUtil.java    From TelePlus-Android with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Sets a {@link MediaFormat} {@link String} value.
 *
 * @param format The {@link MediaFormat} being configured.
 * @param key The key to set.
 * @param value The value to set.
 */
public static void setString(MediaFormat format, String key, String value) {
  format.setString(key, value);
}