Advertisement
thief_g

MergeVideosUsingExoplayer

Apr 27th, 2023
1,040
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.27 KB | None | 0 0
  1. private fun mergeVideos(videoFiles: List<File>, outputFile: File) {
  2.     val extractorFactory = DefaultExtractorsFactory()
  3.     val mediaMuxer = MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)
  4.  
  5.     var videoTrackIndex = -1
  6.     var audioTrackIndex = -1
  7.  
  8.     videoFiles.forEachIndexed { index, videoFile ->
  9.         val dataSourceFactory = DefaultDataSourceFactory(context, "exoplayer")
  10.         val mediaSource = ProgressiveMediaSource.Factory(dataSourceFactory, extractorFactory).createMediaSource(Uri.fromFile(videoFile))
  11.  
  12.         val videoTrack = mediaMuxer.addTrack(mediaSource.getTrackInfo(0))
  13.         val audioTrack = mediaMuxer.addTrack(mediaSource.getTrackInfo(1))
  14.  
  15.         if (index == 0) {
  16.             mediaMuxer.start()
  17.         }
  18.  
  19.         val bufferInfo = MediaCodec.BufferInfo()
  20.         var isFinished = false
  21.  
  22.         var currentSampleTime: Long = 0
  23.         while (!isFinished) {
  24.             val sampleData = ByteArray(1024 * 1024)
  25.             val sampleSize = mediaSource.readData(videoTrack, currentSampleTime, bufferInfo)
  26.             if (sampleSize < 0) {
  27.                 isFinished = true
  28.                 break
  29.             }
  30.             bufferInfo.presentationTimeUs += 1000000L / 30
  31.             bufferInfo.flags = mediaSource.getSampleFlags(videoTrack, bufferInfo.presentationTimeUs)
  32.             mediaMuxer.writeSampleData(videoTrack, ByteBuffer.wrap(sampleData, 0, sampleSize), bufferInfo)
  33.             currentSampleTime = bufferInfo.presentationTimeUs
  34.         }
  35.  
  36.         isFinished = false
  37.         currentSampleTime = 0
  38.         while (!isFinished) {
  39.             val sampleData = ByteArray(1024 * 1024)
  40.             val sampleSize = mediaSource.readData(audioTrack, currentSampleTime, bufferInfo)
  41.             if (sampleSize < 0) {
  42.                 isFinished = true
  43.                 break
  44.             }
  45.             bufferInfo.presentationTimeUs += 1000000L / 30
  46.             bufferInfo.flags = mediaSource.getSampleFlags(audioTrack, bufferInfo.presentationTimeUs)
  47.             mediaMuxer.writeSampleData(audioTrack, ByteBuffer.wrap(sampleData, 0, sampleSize), bufferInfo)
  48.             currentSampleTime = bufferInfo.presentationTimeUs
  49.         }
  50.  
  51.         mediaSource.release()
  52.     }
  53.  
  54.     mediaMuxer.stop()
  55.     mediaMuxer.release()
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement