Android Application

Kotlin 멀티미디어 : 음성 녹음 하기

작성자 임베디드코리아 작성일23-10-23 23:34 조회1,821회 댓글0건

첨부파일

Kotlin 멀티미디어 : 음성 녹음 하기

-------------------------------------------------------------------------------------
      activity_main.xml
-------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button_start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/confirm_botton"
        android:text="녹음 시작"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"/>

    <Button
        android:id="@+id/button_stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/confirm_botton"
        android:text="녹음 마침"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"/>
</LinearLayout>

------------------------------------------------------------------------------------
    botton_true.xml
-- res/drawable
-- New --> Drawable Resource File
-- File Name : button_true  , Root Element : shape
------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle" >
    <solid android:color="#8EC7F4" />
    <stroke android:color="#ff0000ff" android:width="4dp" />
    <padding android:left="7dp" android:top="7dp"
        android:right="7dp" android:bottom="7dp" />
    <corners
        android:radius="30dp"
        android:bottomLeftRadius="30dp"
        android:bottomRightRadius="30dp"
        android:topLeftRadius="30dp"
        android:topRightRadius="30dp" />
</shape>

------------------------------------------------------------------------------------
    botton_false.xml
-- res/drawable
-- New --> Drawable Resource File
-- File Name : button_farse  , Root Element : shape
------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle" >
    <solid android:color="#FFC107" />
    <stroke android:color="#ff0000ff" android:width="4dp" />
    <padding android:left="7dp" android:top="7dp"
        android:right="7dp" android:bottom="7dp" />
    <corners
        android:radius="30dp"
        android:bottomLeftRadius="30dp"
        android:bottomRightRadius="30dp"
        android:topLeftRadius="30dp"
        android:topRightRadius="30dp" />
</shape>

------------------------------------------------------------------------------------
    confirm_botton.xml
-- res/drawable
-- New --> Drawable Resource File
-- File Name : confirm_botton  , Root Element : selector
------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/button_false"></item>
    <item android:state_pressed="false" android:drawable="@drawable/button_true"></item>
</selector>

------------------------------------------------------------------------------------
    MainActivity.kt
------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
    private var outputPath: String? = null
    private var mediaRecorder : MediaRecorder? = null
    private var state : Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        title = "음성 녹음 하기"

        val startBtn = findViewById<Button>(R.id.button_start)
        val stopBtn = findViewById<Button>(R.id.button_stop)

        // 녹음 시작 버튼
        startBtn.setOnClickListener {

            // 권한 부여 여부
            val isEmpower = ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED

            // 권한 부여 되지 않았을경우
            if (isEmpower) {
                empowerRecordAudioAndWriteReadStorage()

                // 권한 부여 되었을 경우
            } else {
                startRecording()
            }

        }


        // 녹음 중지 버튼
        stopBtn.setOnClickListener {
            stopRecording()
        }
    }


    // 레코딩, 파일 읽기 쓰기 권한부여
    private fun empowerRecordAudioAndWriteReadStorage(){

        val permissions = arrayOf(android.Manifest.permission.RECORD_AUDIO, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE)
        ActivityCompat.requestPermissions(this, permissions,0)

    }

    private fun startRecording(){

        val fileName: String = Date().getTime().toString() + ".mp3"

        outputPath = Environment.getExternalStorageDirectory().absolutePath + "/Download/" + fileName //내장메모리 밑에 위치
        mediaRecorder = MediaRecorder()
        mediaRecorder?.setAudioSource((MediaRecorder.AudioSource.MIC))
        mediaRecorder?.setOutputFormat((MediaRecorder.OutputFormat.MPEG_4))
        mediaRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
        mediaRecorder?.setOutputFile(outputPath)

        try {
            mediaRecorder?.prepare()
            mediaRecorder?.start()
            state = true
            Toast.makeText(this, "녹음이 시작되었습니다.", Toast.LENGTH_SHORT).show()
        } catch (e: IllegalStateException){
            e.printStackTrace()
        } catch (e: IOException){
            e.printStackTrace()
        }
    }

    private fun stopRecording(){
        if(state){
            mediaRecorder?.stop()
            mediaRecorder?.reset()
            mediaRecorder?.release()
            state = false
            Toast.makeText(this, "녹음이 되었습니다.", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "녹음 상태가 아닙니다.", Toast.LENGTH_SHORT).show()
        }
    }
}


------------------------------------------------------------------------------------
    themes.xml
------------------------------------------------------------------------------------
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Base.Theme.VoiceRecorder" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">#FF9800</item>
        <item name="colorPrimaryDark">#00897B</item>
    </style>

    <style name="Theme.VoiceRecorder" parent="Base.Theme.VoiceRecorder" />
</resources>