📜  kotlin grabacion de audio (1)

📅  最后修改于: 2023-12-03 15:02:32.158000             🧑  作者: Mango

Kotlin录音

Kotlin是一种基于JVM的编程语言,适用于Android开发,可用于录制音频。在这里,我们将介绍如何使用Kotlin在Android应用程序中录制音频。

需求
  • Android Studio
  • 麦克风权限
  • Android设备或模拟器
步骤
1. 添加权限

先在AndroidManifest.xml文件中添加录音和写文件权限:

<uses-permission android:name="android.permission.RECORD_AUDIO" />    
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2. 添加依赖

在build.gradle文件中添加Kotlin核心库和音频录制库:

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation "com.github.bracode.conducto:conducto-android:0.1.2"
}
3. 编写录音逻辑

创建一个Kotlin类并添加以下方法:

import android.media.AudioRecord
import android.media.MediaRecorder
import java.io.File
import java.io.FileOutputStream

class AudioRecorder(private val outputFile: File) {

    private val audioSource = MediaRecorder.AudioSource.MIC
    private val sampleRate = 44100
    private val channel = android.media.AudioFormat.CHANNEL_IN_STEREO
    private val encode = android.media.AudioFormat.ENCODING_PCM_16BIT
    private val bufferSize = AudioRecord.getMinBufferSize(sampleRate, channel, encode)
    private val audioRecord = AudioRecord(audioSource, sampleRate, channel, encode, bufferSize)
    private var recordingThread: Thread? = null
    private var isRecording = false

    fun startRecording() {
        audioRecord.startRecording()

        isRecording = true
        recordingThread = Thread {
            writeAudioDataToFile()
        }.apply {
            start()
        }
    }

    fun stopRecording() {
        isRecording = false

        try {
            recordingThread?.join()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }

        audioRecord.stop()
        audioRecord.release()
    }

    private fun writeAudioDataToFile() {
        val data = ByteArray(bufferSize)

        FileOutputStream(outputFile).use { fos ->
            while (isRecording) {
                val read = audioRecord.read(data, 0, bufferSize)
                fos.write(data, 0, read)
            }
        }
    }
}

这个类有三个公共方法:

  1. startRecording - 开始录音
  2. stopRecording - 停止录音
  3. isRecording - 是否正在录音
4. 使用录音

我们可以在MainActivity中调用上述类:

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Environment
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.File

class MainActivity : AppCompatActivity() {

    private lateinit var audioRecorder: AudioRecorder

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

        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.RECORD_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.RECORD_AUDIO), 1
            )
        }

        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1
            )
        }

        val outputFile = File(
            Environment.getExternalStorageDirectory().absolutePath,
            "recording.pcm"
        )
        audioRecorder = AudioRecorder(outputFile)

        val startButton = findViewById<Button>(R.id.start_button)
        startButton.setOnClickListener {
            audioRecorder.startRecording()
        }

        val stopButton = findViewById<Button>(R.id.stop_button)
        stopButton.setOnClickListener {
            audioRecorder.stopRecording()
        }
    }
}

代码中包括以下步骤:

  1. 创建一个AudioRecorder对象并传递一个输出文件
  2. 在应用程序启动时检查录音和写权限
  3. 从按钮调用开始和停止录音方法
结论

在Android中使用Kotlin可以很容易地实现录制音频。通过添加权限和依赖项,我们可以快速编写Kotlin类并在MainActivity中使用它来记录音频。