0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Androidで動画を圧縮する

0
Posted at

Media3 Transformer を使用して、Androidで動画を圧縮する方法をメモします。

Gradleへ依存関係を追加します。

implementation("androidx.media3:media3-transformer:x.x.x")
implementation("androidx.media3:media3-effect:x.x.x")

解像度を下げて圧縮する

動画サイズを削減する方法として解像度を変更するのが効果的です。1080p動画を720pへ変換する場合は次のように実装します。

val presentation = Presentation.createForWidthAndHeight(1080, 720, Presentation.LAYOUT_SCALE_TO_FIT)

val editedMediaItem = EditedMediaItem.Builder(MediaItem.fromUri(inputUri) // 圧縮する動画のUri
).setEffects(
    Effects(
        emptyList(),
        listOf(presentation)
    )
).build()

圧縮動画を書き出す

作成した EditedMediaItem を使用して動画を書き出します。

val transformer = Transformer.Builder(context).build()
transformer.start(editedMediaItem, outputFile.absolutePath)

変換完了後の処理

もし変換完了後の処理を行いたい場合は次のように記述します。

val transformer = Transformer.Builder(context)
    .addListener(
        object : Transformer.Listener {
            override fun onCompleted(
                composition: Composition,
                exportResult: ExportResult
            ) {
                Log.d("Transformer", "変換完了です")
            }
            override fun onError(
                composition: Composition,
                exportResult: ExportResult,
                exportException: ExportException
            ) {
                Log.e("Transformer", "変換に失敗しました。")
            }
        }
    ).build()
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?