前面的文章我们讲解的是OpenSL ES音频播放,OpenSL ES非常强大,有音频播放当然有录音,这样才可以完成前面所说的C层完成音频的转发到服务器。
下面我们编写OpenSL PCM录音,完成的功能是录制麦克风的声音存储PCM到data私有目录。
一、 Eclipse 创建Android工程
二、布局XML 创建文件 /res/layout/open_sl_audio_record.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="暂停" />
</LinearLayout>
</LinearLayout>
布局文件:开始和暂停两个Button控制录音
三、Activity类 创建/src/com/example/testopensl/AudioRecordActivity.java
package com.example.testopensl;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import com.example.audio.R;
public class AudioRecordActivity extends Activity implements OnClickListener {
static {
System.loadLibrary("TestAudio");
}
private boolean mRecording;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open_sl_audio_record);
findViewById(R.id.start).setOnClickListener(this);
findViewById(R.id.stop).setOnClickListener(this);
createEngine();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
File file = new File(getCacheDir(), "audio.pcm");
createAudioRecord(file.getAbsolutePath());
mRecording = true;
break;
case R.id.stop:
stop();
mRecording = false;
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mRecording) {
stop();
}
shutdown();
}
/** Native methods, implemented in jni folder */
public native void createEngine();
public native void createAudioRecord(String uri);
public native void stop();
public native void shutdown();
}
文件存储位置:/data/data/com.example.audio/cache/audio.pcm
四、编写日志头文件,用于日志输出, 创建/jni/log.h 文件#ifndef LOG_H_
#define LOG_H_
#include <android/log.h>
#ifndef DGB
#define DGB 0
#endif
#ifndef LOG_TAG
#define LOG_TAG __FILE__
#endif
#ifndef ALOGD
#if DGB
#define ALOGD(...) \
__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#else
#define ALOGD(...) ((void)0)
#endif
#endif
#endif /* LOG_H_ */
五、用javah命令 生成jni 头文件. 文件目录/jni/com_example_testo