Android:使用MediaRecorder录制音频
class RecorderActivity : AppCompatActivity() {
val directory: String = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).absolutePath
val recorder = MediaRecorder()
var isPause = true
var time = 0
val loop: ThreadUtils.Loop = ThreadUtils.Loop(1000).loop {
if (!isPause) {
rTimer.text = "${time++}"
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recoder)
rRecorder.setOnTouchListener { view, motionEvent ->
when (motionEvent.action) {
MotionEvent.ACTION_DOWN -> {
start()
}
MotionEvent.ACTION_UP -> {
pause()
}
}
true
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC)
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB)
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB)
if (Build.VERSION.SDK_INT >= 10) {
recorder.setAudioSamplingRate(44100)
recorder.setAudioEncodingBitRate(96000)
} else {
// older version of Android, use crappy sounding voice codec
recorder.setAudioSamplingRate(8000)
recorder.setAudioEncodingBitRate(12200)
}
recorder.setOutputFile("$directory/${()}.amr")
recorder.prepare()
}
fun start() {
if (isPause) {
isPause = false
recorder.start()
loop.start()
}
}
fun pause() {
if (!isPause) {
isPause = true
//recorder.pause() API 24
}
}
fun stop() {
loop.destroy()
recorder.stop()
recorder.release()
}
override fun onDestroy() {
stop()
super.onDestroy()
}
}