项目中遇到需求,采集音频上传至公司编译的sdk内,播放sdk传递过来的音频,所以自行实现了一个采集音频与播放音频的方法
代码:
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioRecord
import android.media.AudioTrack
import android.media.MediaRecorder
import android.media.audiofx.AcousticEchoCanceler
import android.util.Log
import android.widget.LinearLayout
import androidx.core.app.ActivityCompat
import com.brainmed.mvdplayer.OpenTalkingBean
import com.google.gson.Gson
import com.lzf.easyfloat.EasyFloat
import com.mohism.medtion.ext.gone
import com.mohism.medtion.ext.visible
import com.mohism.medtion.ui.elab.player.NyhMvdPlayerManger
import com.mohism.medtion.ui.elab.player.enums.NyhMvdErrorEnum
import java.io.ByteArrayOutputStream
import java.util.Arrays
import java.util.concurrent.LinkedBlockingQueue
/**
* @author 马自强
*
* 2024-02-22 10:00:00
*
* 对讲功能
*/
class NyhMvdVoiceManger private constructor() {
//服务器Id
var hDevice: Long? = null
var isTalkingOpen = false
private var isVoice = false
private var audioRecord: AudioRecord? = null
private val outputStream = ByteArrayOutputStream()
private var audioTrack: AudioTrack? = null
private val audioDataQueue = LinkedBlockingQueue<ByteArray>() // 使用线程安全的队列类
private val len = 1024
private val buffer = ByteArray(len)
// 声明线程变量以便后续关闭
private var audioCaptureThread: Thread? = null
private var audioPlayThread: Thread? = null
private var mActivity: Activity? = null
private val channelConfig = AudioFormat.CHANNEL_IN_DEFAULT
private var bufferSize = 0
companion object {
// 使用volatile关键字确保可见性和禁止指令重排序
@Volatile
private var mInstance: NyhMvdVoiceManger? = null
@JvmStatic
fun instance(): NyhMvdVoiceManger {
// 双重检查锁定,确保线程安全
if (mInstance == null) {
synchronized(this) {
if (mInstance == null) {
mInstance = NyhMvdVoiceManger()
}
}
}
return mInstance!!
}
}
/**
*
标签:AudioTrack,音频,private,AudioRecord,var,import,android,null,com
From: https://blog.csdn.net/maziqiang1993/article/details/135462637