以下是一个简单的实现,仅供参考:
Step 1:添加依赖
在工程build.gradle文件中添加以下依赖:
groovy Copy code
allprojects {
repositories {
google()
jcenter()
}
}
dependencies {
implementation "com.android.support:appcompat-v7:${supportLibVersion}"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "com.google.android.material:material:${materialVersion}"
implementation "com.google.guava:guava:${guavaVersion}"
implementation "com.google.code.gson:gson:${gsonVersion}"
implementation "com.squareup.okhttp3:okhttp:${okhttpVersion}"
implementation "com.jakewharton.timber:timber:${timberVersion}"
implementation("com.google.android.exoplayer:exoplayer-core:${exoPlayerVersion}")
implementation("com.google.android.exoplayer:exoplayer-ui:${exoPlayerVersion}")
implementation("com.google.android.obbdownloader:downloader:${downloaderVersion}")
implementation("com.google.android.obbdownloader:downloader-impl:${downloaderVersion}")
implementation("com.google.android.obbdownloader:zipfile:${downloaderVersion}")
implementation("de.greenrobot:eventbus:${eventBusVersion}")
}
注意:oboe库并不属于谷歌官方的安卓库,需要手动下载并添加到工程中。下载地址:https://github.com/google/oboe。
Step 2:创建录音和播放类
在kotlin包下创建两个类:AudioRecorder和AudioPlayer。这两个类都继承自一个基类:AudioBase。
kotlin Copy code
abstract class AudioBase {
protected val TAG = javaClass.simpleName
protected var sampleRate: Int = SAMPLE_RATE
protected var channelCount: Int = CHANNEL_COUNT
protected var bitDepth: Int = BIT_DEPTH
abstract fun start()
abstract fun stop()
abstract fun release()
fun setSampleRate(sampleRate: Int) {
this.sampleRate = sampleRate
}
fun setChannelCount(channelCount: Int) {
this.channelCount = channelCount
}
fun setBitDepth(bitDepth: Int) {
this.bitDepth = bitDepth
}
interface ExceptionHandler {
fun onException(e: Exception)
}
interface VolumeHandler {
fun onVolume(volume: Float)
}
companion object {
const val SAMPLE_RATE = 44100
const val CHANNEL_COUNT = 1
const val BIT_DEPTH = 16
}
}
AudioBase类定义了三个基础的属性:采样率(sampleRate)、通道数(channelCount)和位宽(bitDepth)。还定义了三个抽象方法:开始(start)、停止(stop)和释放(release)。并提供了异常(ExceptionHandler)和音量(VolumeHandler)回调。
AudioRecorder和AudioPlayer类都继承了AudioBase类,并实现其三个抽象方法。
kotlin Copy code
class AudioRecorder(private val audioFile: File) : AudioBase() {
private val oboeRecorder: OboeRecorder by lazy {
OboeRecorder(sampleRate, channelCount, bitDepth, audioFile)
}
private var exceptionHandler: ExceptionHandler? = null
private var volumeHandler: VolumeHandler? = null
override fun start() {
try {
oboeRecorder.start()
} catch (e: Exception) {
exceptionHandler?.onException(e)
}
}
override fun stop() {
oboeRecorder.stop()
}
override fun release() {
oboeRecorder.release()
}
fun setExceptionHandler(listener: ExceptionHandler) {
exceptionHandler = listener
}
fun setVolumeHandler(listener: VolumeHandler) {
volumeHandler = listener
oboeRecorder.setVolumeHandler(object : OboeRecorder.VolumeHandler {
override fun onVolume(volume: Float) {
volumeHandler?.onVolume(volume)
}
})
}
}
kotlin Copy code
class AudioPlayer(private val audioFile: File) : AudioBase() {
private val oboePlayer: OboePlayer by lazy {
OboePlayer(sampleRate, channelCount, bitDepth, audioFile)
}
private var exceptionHandler: ExceptionHandler? = null
private var volumeHandler: VolumeHandler? = null
override fun start() {
try {
oboePlayer.start()
} catch (e: Exception) {
exceptionHandler?.onException(e)
}
}
override fun stop() {
oboePlayer.stop()
}
override fun release() {
oboePlayer.release()
}
fun setExceptionHandler(listener: ExceptionHandler) {
exceptionHandler = listener
}
fun setVolumeHandler(listener: VolumeHandler) {
volumeHandler = listener
oboePlayer.setVolumeHandler(object : OboePlayer.VolumeHandler {
override fun onVolume(volume: Float) {
volumeHandler?.onVolume(volume)
}
})
}
}
注意:AudioRecorder和AudioPlayer类内部实例化了OboeRecorder和OboePlayer对象,这两个对象是一个JNI库文件(so文件)封装,实现了与AudioRecord和AudioTrack对象相同的功能,但可靠性和性能更高。
在这两个类中,start方法将开始录音或播放。stop方法将停止录音或播放。release方法将释放占用的资源。
setExceptionHandler和setVolumeHandler方法分别用于异常处理和音量监测。
Step 3:创建JNI类
为了使用oboe库进行录音和播放,我们需要封装其API,并在JNI层实现。因此,我们需要在Java包下创建一个类:OboeRecorder和OboePlayer。这两个类继承自同一个OboeBase基类。
java Copy code
public abstract class OboeBase {
protected int sampleRate;
protected int channelCount;
protected int bitDepth;
public OboeBase(int sampleRate, int channelCount, int bitDepth) {
this.sampleRate = sampleRate;
this.channelCount = channelCount;
this.bitDepth = bitDepth;
}
public abstract void start() throws Exception;
public abstract void stop();
public abstract void release();
public interface VolumeHandler {
void onVolume(float volume);
}
protected abstract void setVolumeHandler(VolumeHandler handler);
public interface ExceptionHandler {
void onException(Exception e);
}
protected abstract void setExceptionHandler(ExceptionHandler handler);
/**
* 根据bitDepth的值判断是否支持该位宽
*/
protected static boolean isBitDepthSupported(int bitDepth) {
switch (bitDepth) {
case 16:
return true;
case 24:
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
case 32:
case 64:
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
case -32:
case -64:
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
default:
return false;
}
}
}
OboeBase类定义了与AudioBase类相同的三个基本属性:采样率(sampleRate)、通道数(channelCount)和位宽(bitDepth)。还定义了三个抽象方法:开始(start)、停止(stop)和释放(release)。并提供了异常(ExceptionHandler)和音量(VolumeHandler)回调。
注意:OboeRecorder和OboePlayer类中加载了JNI库文件,并使用JNI方法实现了录音和播放的功能。这些JNI方法是在C++代码中实现的。详细实现过程可以参考oboe官方文档。
OboeRecorder类在start方法中启动了一个线程来记录录音,stop方法停止线程。OboePlayer类在start方法中从文件中读取数据并播放,stop方法停止播放。
Step 4:使用录音和播放类
在kotlin层使用AudioRecorder和AudioPlayer类时,只需要实例化对象并调用对应的方法即可。
kotlin Copy code
val recorder = AudioRecorder(File("/storage/emulated/0/Download/test.pcm"))
recorder.start()
handlers[0] = object : AudioBase.ExceptionHandler {
override fun onException(e: Exception) {
Timber.tag("audioRecorder").e("record exception: ${e.message}")
}
}
handlers[1] = object : AudioBase.VolumeHandler {
override fun onVolume(volume: Float) {
// do something...
}
}
recorder.setExceptionHandler(handlers[0]!!)
recorder.setVolumeHandler(handlers[1]!!)
recorder.stop()
recorder.release()
val player = AudioPlayer(File("/storage/emulated/0/Download/test.pcm"))
player.start()
handlers[0] = object : AudioBase.ExceptionHandler {
override fun onException(e: Exception) {
Timber.tag("audioPlayer").e("play exception: ${e.message}")
}
}
handlers[1] = object : AudioBase.VolumeHandler {
override fun onVolume(volume: Float) {
// do something...
}
}
player.setExceptionHandler(handlers[0]!!)
player.setVolumeHandler(handlers[1]!!)
player.stop()
player.release()
注意:这里使用了Timber库打印日志,需要手动添加依赖,建议在开发和测试阶段使用,生产环境需要关掉日志。
另外,audio_temp.pcm必须是以raw PCM格式录制的音频数据,并且必须在OboeRecorder.start()方法之前存储。
由于oboe库在一些Android版本上可能存在不稳定性,因此需要进行多设备测试,并针对不同的Android版本进行适配和调整。此外,在录制过程中需要对录音权限、录音设备是否被占用、SD卡可写性等进行检查和处理。具体方式可以参考官方文档或第三方库。