Skip to content

Instantly share code, notes, and snippets.

@reuniware
Created December 10, 2019 10:26
Show Gist options
  • Save reuniware/4b27eb094d8212768e1b185096203b03 to your computer and use it in GitHub Desktop.
Save reuniware/4b27eb094d8212768e1b185096203b03 to your computer and use it in GitHub Desktop.
(Android/Kotlin) Record Audio from MIC to .3GP file (that can be read with VLC).
// https://ntic974.blogspot.com
package com.reuniware.poneyvid
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaRecorder
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import androidx.core.app.ActivityCompat
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
val REQUEST_MEDIA_PROJECTION = 5555
val REQUEST_AUDIO = 7777
val REQUEST_STORAGE = 9999
lateinit var manager : MediaProjectionManager
lateinit var projection : MediaProjection
lateinit var recorder : MediaRecorder
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.RECORD_AUDIO),
REQUEST_AUDIO
)
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_STORAGE
)
}
if (!::manager.isInitialized) {
manager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION)
}
buttonStart.setOnClickListener {
val PATH_NAME = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath + "/recorded.3gp" //+ "/mavid.mp4"
recorder = MediaRecorder()
recorder.setAudioSource(MediaRecorder.AudioSource.MIC)
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
recorder.setOutputFile(PATH_NAME)
recorder.prepare()
recorder.start() // Recording is now started
}
buttonStop.setOnClickListener {
recorder.stop()
recorder.reset()
recorder.release()
}
}
var resultCode_ = -1
var data_ = Intent()
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (!::projection.isInitialized) {
resultCode_ = resultCode
data_ = data!!
projection = manager.getMediaProjection(resultCode, data) as MediaProjection
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment