Skip to content

Instantly share code, notes, and snippets.

@bitristan
Created July 31, 2020 03:12
Show Gist options
  • Save bitristan/01ce2b4ef943293d61c9fc84b45d6b5a to your computer and use it in GitHub Desktop.
Save bitristan/01ce2b4ef943293d61c9fc84b45d6b5a to your computer and use it in GitHub Desktop.
录音
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import android.widget.Button
import java.io.*
import java.lang.Exception
class MainActivity : AppCompatActivity(), View.OnClickListener {
private var mRecordBufferSize = 0
private var mRecordInstance: AudioRecord? = null
private var saveVoiceByte: ByteArrayOutputStream? = null
private var isRecord = false
override fun onClick(v: View?) {
when (v?.id) {
R.id.start -> {
isRecord = true
Thread {
startRecord()
}.start()
Handler().postDelayed({
stopRecord()
}, 60000)
}
R.id.stop -> {
stopRecord()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.start).setOnClickListener(this)
findViewById<Button>(R.id.stop).setOnClickListener(this)
val file = File(AUDIO_FILE)
val data = file.readBytes()
Log.d(TAG, "data size: ${data.size}")
}
private fun stopRecord() {
Log.d(TAG, "stop record")
if (mRecordInstance != null) {
mRecordInstance?.stop()
mRecordInstance?.release()
mRecordInstance = null
isRecord = false
}
}
private fun startRecord() {
Log.d(TAG, "start record")
try {
val channelConfiguration = AudioFormat.CHANNEL_IN_MONO
val audioEncodingBits = AudioFormat.ENCODING_PCM_16BIT
mRecordBufferSize =
AudioRecord.getMinBufferSize(SAMPLE_RATE, channelConfiguration, audioEncodingBits)
mRecordInstance = AudioRecord(
MediaRecorder.AudioSource.MIC, SAMPLE_RATE, channelConfiguration,
audioEncodingBits, mRecordBufferSize
)
mRecordInstance?.channelCount
val file = File(AUDIO_FILE)
if (file.exists()) {
file.delete()
}
val fos = FileOutputStream(file)
if (mRecordInstance != null && mRecordInstance?.state == AudioRecord.STATE_INITIALIZED) {
mRecordInstance?.startRecording()
}
val audiodata = ByteArray(mRecordBufferSize)
var readsize: Int
saveVoiceByte = ByteArrayOutputStream()
while (isRecord) {
readsize = mRecordInstance!!.read(audiodata, 0, mRecordBufferSize)
if (AudioRecord.ERROR_INVALID_OPERATION != readsize) {
saveVoiceByte?.write(audiodata, 0, readsize)
fos.write(audiodata, 0, readsize)
}
}
saveVoiceByte?.close()
fos.close()
} catch (e: Exception) {
Log.e(TAG, "error start record.", e)
}
}
companion object {
private const val TAG = "MainActivity"
private const val AUDIO_FILE = "/sdcard/test.pcm"
private const val SAMPLE_RATE = 16000
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment