JNI在Android开发中的应用之--用AudioRecord录音,用AudioTrack播放声音.

[java] view plain copy print ?
  1. 下面是主Activity.  
  2.   
  3. package com.example.hellojni;  
  4.   
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.Button;  
  11.   
  12. import java.io.BufferedOutputStream;  
  13. import java.io.File;  
  14. import java.io.FileNotFoundException;  
  15. import java.io.FileOutputStream;  
  16. import java.io.IOException;  
  17.   
  18.   
  19. public class HelloJni extends Activity  
  20. {  
  21.   
  22.     Button startRecord;  
  23.     Button stopRecord;  
  24.     Button play;  
  25.     static BufferedOutputStream bos;  
  26.   
  27.     static {  
  28.         System.loadLibrary("hello-jni");  
  29.     }  
  30.   
  31.   
  32.     /** Called when the activity is first created. */  
  33.     @Override  
  34.     public void onCreate(Bundle savedInstanceState)  
  35.     {  
  36.         super.onCreate(savedInstanceState);  
  37.   
  38.         setContentView(R.layout.main);  
  39.   
  40.         startRecord = (Button)findViewById(R.id.start);  
  41.         stopRecord = (Button)findViewById(R.id.stop);  
  42.         play  =(Button)findViewById(R.id.play);  
  43.   
  44.   
  45.         startRecord.setOnClickListener(new OnClickListener() {  
  46.             @Override  
  47.             public void onClick(View v) {  
  48.                 new Thread(){  
  49.                     public void run(){  
  50.   
  51.                         initOutputStream();  
  52.   
  53.                         startRecord();  
  54.                     }  
  55.                 }.start();  
  56.   
  57.             }  
  58.         });  
  59.   
  60.   
  61.         stopRecord.setOnClickListener(new OnClickListener() {  
  62.             @Override  
  63.             public void onClick(View v) {  
  64.                 new Thread(){  
  65.                     public void run(){  
  66.                         stopRecord();  
  67.   
  68.                         try{  
  69.                             Thread.sleep(1000*2);  
  70.                             if(bos!=null){  
  71.                                 try {  
  72.                                     bos.close();  
  73.                                 } catch (IOException e) {  
  74.                                     // TODO Auto-generated catch block   
  75.                                     e.printStackTrace();  
  76.                                 }  
  77.                             }  
  78.                         }catch(Exception e){  
  79.   
  80.                         }  
  81.                     }  
  82.                 }.start();  
  83.   
  84.             }  
  85.         });  
  86.   
  87.         play.setOnClickListener(new OnClickListener() {  
  88.             @Override  
  89.             public void onClick(View v) {  
  90.                 new Thread(){public void run(){play();}}.start();  
  91.             }  
  92.         });  
  93.   
  94.     }  
  95.   
  96.   
  97.     public void initOutputStream(){  
  98.             File file = new File("/sdcard/temp.pcm");  
  99.             try {  
  100.                 bos = new BufferedOutputStream(new FileOutputStream(file));  
  101.             } catch (FileNotFoundException e) {  
  102.                 e.printStackTrace();  
  103.             }  
  104.   
  105.     }  
  106.     public static void receiveAudioData(byte[] data,int size){  
  107.             try {  
  108.                 bos.write(data);  
  109.                 bos.flush();  
  110.             } catch (IOException e) {  
  111.                 e.printStackTrace();  
  112.             }  
  113.     }  
  114.   
  115.     public native void startRecord();  
  116.     public native void stopRecord();  
  117.     public native void play();  
  118.   
  119.   
  120. }  
下面是主Activity.

package com.example.hellojni;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class HelloJni extends Activity
{

	Button startRecord;
	Button stopRecord;
	Button play;
	static BufferedOutputStream bos;

    static {
        System.loadLibrary("hello-jni");
    }


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        startRecord = (Button)findViewById(R.id.start);
        stopRecord = (Button)findViewById(R.id.stop);
        play  =(Button)findViewById(R.id.play);


        startRecord.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new Thread(){
					public void run(){

						initOutputStream();

						startRecord();
					}
				}.start();

			}
		});


        stopRecord.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new Thread(){
					public void run(){
						stopRecord();

						try{
							Thread.sleep(1000*2);
							if(bos!=null){
								try {
									bos.close();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}catch(Exception e){

						}
					}
				}.start();

			}
		});

        play.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new Thread(){public void run(){play();}}.start();
			}
		});

    }


    public void initOutputStream(){
    		File file = new File("/sdcard/temp.pcm");
    		try {
				bos = new BufferedOutputStream(new FileOutputStream(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}

    }
    public static void receiveAudioData(byte[] data,int size){
    		try {
				bos.write(data);
				bos.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
    }

    public native void startRecord();
    public native void stopRecord();
    public native void play();


}

 

布局文件:

 

[html] view plain copy print ?
  1. xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <Button android:id="@+id/start"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="用AudioRecord录音"/>  
  11.   
  12.     <Button android:id="@+id/stop"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:text="停止录音"/>  
  16.   
  17.     <Button android:id="@+id/play"  
  18.         android:layout_width="wrap_content"  
  19.         android:layout_height="wrap_content"  
  20.         android:text="用AudioTrack播放"/>  
  21.   
  22.   
  23.     <Button android:id="@+id/stop"  
  24.         android:layout_width="wrap_content"  
  25.         android:layout_height="wrap_content"  
  26.         android:text="底层在录音哦,请点击我,我反应很快的耶,没有阻塞UI线程"/>  
  27.   
  28. LinearLayout>  



	

 

接下来是hello-jni.c:

 

 

[cpp] view plain copy print ?
  1. #include    
  2. #include    
  3. #include    
  4. #include    
  5. #include    
  6.   
  7. static JNIEnv* (*jni_env);  
  8. static jbyteArray buffer;  
  9. static jobject audio_track;  
  10. static jint buffer_size;  
  11. static jmethodID method_write;  
  12.   
  13. #define AUDIO_SOURCE_VOICE_COMMUNICATION (7)   
  14. #define AUDIO_SOURCE_MIC (1)   
  15. #define SAMPLE_RATE_IN_HZ (11025)   
  16. #define CHANNEL_CONFIGURATION_MONO (16)   
  17. #define ENCODING_PCM_16BIT (2)   
  18.   
  19. #define LOG_TAG "test"   
  20. #define LOGI(f,v)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,f,v)   
  21. #define LOGI2(a)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,a)   
  22.   
  23.   
  24. static int run= 1;  
  25. void  Java_com_example_hellojni_HelloJni_stopRecord(JNIEnv* jni_env,  
  26.         jobject thiz){  
  27.     run = 0;  
  28. }  
  29. void  Java_com_example_hellojni_HelloJni_startRecord(JNIEnv* jni_env,  
  30.         jobject thiz){  
  31.   
  32.     jclass audio_record_class =(*jni_env)->FindClass(jni_env,"android/media/AudioRecord");  
  33.   
  34.     jmethodID constructor_id = (*jni_env)->GetMethodID(jni_env,audio_record_class, "",  
  35.                 "(IIIII)V");  
  36.   
  37.     jmethodID min_buff_size_id = (*jni_env)->GetStaticMethodID(jni_env,audio_record_class,  
  38.                 "getMinBufferSize""(III)I");  
  39.   
  40.     jint buff_size  
  41.                 = (*jni_env)->CallStaticIntMethod(jni_env,audio_record_class,  
  42.                         min_buff_size_id,  
  43.                         SAMPLE_RATE_IN_HZ,  
  44.                         CHANNEL_CONFIGURATION_MONO,  
  45.                         ENCODING_PCM_16BIT);  
  46.   
  47.     jobject audioRecord = (*jni_env)->NewObject(jni_env,audio_record_class, constructor_id,  
  48.     //          AUDIO_SOURCE_MIC,   
  49.                 AUDIO_SOURCE_VOICE_COMMUNICATION,  
  50.                 SAMPLE_RATE_IN_HZ,  
  51.                 CHANNEL_CONFIGURATION_MONO,  
  52.                 ENCODING_PCM_16BIT,  
  53.                 buff_size);  
  54.   
  55.     LOGI2("startRecording");  
  56.     jmethodID record_id = (*jni_env)->GetMethodID(jni_env,audio_record_class, "startRecording",  
  57.                 "()V");  
  58.   
  59.     //start recording   
  60.     (*jni_env)->CallVoidMethod(jni_env,audioRecord, record_id);  
  61.     LOGI2("after call startRecording");  
  62.     jmethodID read_id = (*jni_env)->GetMethodID(jni_env,audio_record_class, "read""([BII)I");  
  63.   
  64.   
  65.     int nread = 0;  
  66.     int blockSize = 100;  
  67.     jbyteArray read_buff = (*jni_env)->NewByteArray(jni_env,blockSize);  
  68.     jbyteArray aes_bytes = (*jni_env)->NewByteArray(jni_env,blockSize);  
  69.   
  70.     jbyte* audio_bytes;  
  71.   
  72.     FILE* fp = fopen("/sdcard/temp.pcm","ab");  
  73.     LOGI2("after fopen");  
  74.   
  75.     //   
  76.     jclass HelloJniCls =(*jni_env)->FindClass(jni_env,"com/example/hellojni/HelloJni");  
  77.     jmethodID receiveAudioData = (*jni_env)->GetStaticMethodID(jni_env,HelloJniCls,"receiveAudioData",  
  78.             "([BI)V");  
  79.   
  80.     while (run) {  
  81.   
  82.             nread = (*jni_env)->CallIntMethod(jni_env,audioRecord,read_id, read_buff, 0, blockSize);  
  83.             if(nread<=0){  
  84.                 break;  
  85.             }  
  86.   
  87.             audio_bytes = (jbyte*)calloc(nread,1);  
  88.   
  89.             (*jni_env)->GetByteArrayRegion(jni_env,read_buff, 0, nread,audio_bytes);  
  90. //          fwrite(audio_bytes, 1, nread, fp);   
  91.   
  92.             (*jni_env)->CallStaticVoidMethod(jni_env,HelloJniCls, receiveAudioData, read_buff,nread);  
  93.             usleep(50);  
  94.     }  
  95. }  
  96.   
  97. void  Java_com_example_hellojni_HelloJni_play(JNIEnv* jni_env,  
  98.         jobject thiz){  
  99.       LOGI2("after Java_com_example_hellojni_HelloJni_play");  
  100.   
  101. //  (*jni_env) = jni_env;   
  102.     jclass audio_track_cls = (*jni_env)->FindClass(jni_env,"android/media/AudioTrack");  
  103.     jmethodID min_buff_size_id = (*jni_env)->GetStaticMethodID(  
  104.                                          jni_env,  
  105.                                          audio_track_cls,  
  106.                                         "getMinBufferSize",  
  107.                                         "(III)I");  
  108.     buffer_size = (*jni_env)->CallStaticIntMethod(jni_env,audio_track_cls,min_buff_size_id,  
  109.                 11025,  
  110.                 2,          /*CHANNEL_CONFIGURATION_MONO*/  
  111.                 2);         /*ENCODING_PCM_16BIT*/  
  112.     LOGI("buffer_size=%i",buffer_size);  
  113.     buffer = (*jni_env)->NewByteArray(jni_env,buffer_size/4);  
  114.   
  115.     char buf[buffer_size/4];  
  116.   
  117.     jmethodID constructor_id = (*jni_env)->GetMethodID(jni_env,audio_track_cls, "",  
  118.             "(IIIIII)V");  
  119.     audio_track = (*jni_env)->NewObject(jni_env,audio_track_cls,  
  120.             constructor_id,  
  121.             3,            /*AudioManager.STREAM_MUSIC*/  
  122.             11025,        /*sampleRateInHz*/  
  123.             2,            /*CHANNEL_CONFIGURATION_MONO*/  
  124.             2,            /*ENCODING_PCM_16BIT*/  
  125.             buffer_size,  /*bufferSizeInBytes*/  
  126.             1             /*AudioTrack.MODE_STREAM*/  
  127.     );  
  128.   
  129.     //setvolume   
  130.     LOGI2("setStereoVolume 1");  
  131.     jmethodID setStereoVolume = (*jni_env)->GetMethodID(jni_env,audio_track_cls,"setStereoVolume","(FF)I");  
  132.     (*jni_env)->CallIntMethod(jni_env,audio_track,setStereoVolume,1.0,1.0);  
  133.     LOGI2("setStereoVolume 2");  
  134.     //play   
  135.     jmethodID method_play = (*jni_env)->GetMethodID(jni_env,audio_track_cls, "play",  
  136.             "()V");  
  137.     (*jni_env)->CallVoidMethod(jni_env,audio_track, method_play);  
  138.   
  139.     //write   
  140.     method_write = (*jni_env)->GetMethodID(jni_env,audio_track_cls,"write","([BII)I");  
  141.   
  142.    FILE* fp = fopen("/sdcard/temp.pcm","rb");  
  143.    LOGI2("after open");  
  144.    int i=0;  
  145.    while(!feof(fp)){  
  146.        jint read= fread(buf,sizeof(char),200,fp);  
  147.        (*jni_env)->SetByteArrayRegion(jni_env,buffer, 0,read, (jbyte *)buf);  
  148.   
  149.        (*jni_env)->CallVoidMethod(jni_env,audio_track,method_write,buffer,0,read);  
  150.    }  
  151.   
  152. }  
#include 
#include 
#include 
#include 
#include 

static JNIEnv* (*jni_env);
static jbyteArray buffer;
static jobject audio_track;
static jint buffer_size;
static jmethodID method_write;

#define AUDIO_SOURCE_VOICE_COMMUNICATION (7)
#define AUDIO_SOURCE_MIC (1)
#define SAMPLE_RATE_IN_HZ (11025)
#define CHANNEL_CONFIGURATION_MONO (16)
#define ENCODING_PCM_16BIT (2)

#define LOG_TAG "test"
#define LOGI(f,v)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,f,v)
#define LOGI2(a)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,a)


static int run= 1;
void  Java_com_example_hellojni_HelloJni_stopRecord(JNIEnv* jni_env,
		jobject thiz){
	run = 0;
}
void  Java_com_example_hellojni_HelloJni_startRecord(JNIEnv* jni_env,
		jobject thiz){

	jclass audio_record_class =(*jni_env)->FindClass(jni_env,"android/media/AudioRecord");

	jmethodID constructor_id = (*jni_env)->GetMethodID(jni_env,audio_record_class, "",
				"(IIIII)V");

	jmethodID min_buff_size_id = (*jni_env)->GetStaticMethodID(jni_env,audio_record_class,
				"getMinBufferSize", "(III)I");

	jint buff_size
				= (*jni_env)->CallStaticIntMethod(jni_env,audio_record_class,
						min_buff_size_id,
						SAMPLE_RATE_IN_HZ,
						CHANNEL_CONFIGURATION_MONO,
						ENCODING_PCM_16BIT);

	jobject audioRecord = (*jni_env)->NewObject(jni_env,audio_record_class, constructor_id,
	//			AUDIO_SOURCE_MIC,
				AUDIO_SOURCE_VOICE_COMMUNICATION,
				SAMPLE_RATE_IN_HZ,
				CHANNEL_CONFIGURATION_MONO,
				ENCODING_PCM_16BIT,
				buff_size);

	LOGI2("startRecording");
	jmethodID record_id = (*jni_env)->GetMethodID(jni_env,audio_record_class, "startRecording",
				"()V");

	//start recording
	(*jni_env)->CallVoidMethod(jni_env,audioRecord, record_id);
	LOGI2("after call startRecording");
	jmethodID read_id = (*jni_env)->GetMethodID(jni_env,audio_record_class, "read", "([BII)I");


	int nread = 0;
	int blockSize = 100;
	jbyteArray read_buff = (*jni_env)->NewByteArray(jni_env,blockSize);
	jbyteArray aes_bytes = (*jni_env)->NewByteArray(jni_env,blockSize);

	jbyte* audio_bytes;

	FILE* fp = fopen("/sdcard/temp.pcm","ab");
	LOGI2("after fopen");

	//
	jclass HelloJniCls =(*jni_env)->FindClass(jni_env,"com/example/hellojni/HelloJni");
	jmethodID receiveAudioData = (*jni_env)->GetStaticMethodID(jni_env,HelloJniCls,"receiveAudioData",
			"([BI)V");

	while (run) {

			nread = (*jni_env)->CallIntMethod(jni_env,audioRecord,read_id, read_buff, 0, blockSize);
			if(nread<=0){
				break;
			}

			audio_bytes = (jbyte*)calloc(nread,1);

			(*jni_env)->GetByteArrayRegion(jni_env,read_buff, 0, nread,audio_bytes);
//			fwrite(audio_bytes, 1, nread, fp);

			(*jni_env)->CallStaticVoidMethod(jni_env,HelloJniCls, receiveAudioData, read_buff,nread);
			usleep(50);
	}
}

void  Java_com_example_hellojni_HelloJni_play(JNIEnv* jni_env,
		jobject thiz){
	  LOGI2("after Java_com_example_hellojni_HelloJni_play");

//	(*jni_env) = jni_env;
	jclass audio_track_cls = (*jni_env)->FindClass(jni_env,"android/media/AudioTrack");
	jmethodID min_buff_size_id = (*jni_env)->GetStaticMethodID(
										 jni_env,
										 audio_track_cls,
										"getMinBufferSize",
										"(III)I");
	buffer_size = (*jni_env)->CallStaticIntMethod(jni_env,audio_track_cls,min_buff_size_id,
			    11025,
			    2,			/*CHANNEL_CONFIGURATION_MONO*/
				2);         /*ENCODING_PCM_16BIT*/
	LOGI("buffer_size=%i",buffer_size);
	buffer = (*jni_env)->NewByteArray(jni_env,buffer_size/4);

	char buf[buffer_size/4];

	jmethodID constructor_id = (*jni_env)->GetMethodID(jni_env,audio_track_cls, "",
			"(IIIIII)V");
	audio_track = (*jni_env)->NewObject(jni_env,audio_track_cls,
			constructor_id,
			3, 			  /*AudioManager.STREAM_MUSIC*/
			11025,        /*sampleRateInHz*/
			2,			  /*CHANNEL_CONFIGURATION_MONO*/
			2,			  /*ENCODING_PCM_16BIT*/
			buffer_size,  /*bufferSizeInBytes*/
			1			  /*AudioTrack.MODE_STREAM*/
	);

	//setvolume
	LOGI2("setStereoVolume 1");
	jmethodID setStereoVolume = (*jni_env)->GetMethodID(jni_env,audio_track_cls,"setStereoVolume","(FF)I");
	(*jni_env)->CallIntMethod(jni_env,audio_track,setStereoVolume,1.0,1.0);
	LOGI2("setStereoVolume 2");
	//play
    jmethodID method_play = (*jni_env)->GetMethodID(jni_env,audio_track_cls, "play",
			"()V");
    (*jni_env)->CallVoidMethod(jni_env,audio_track, method_play);

    //write
    method_write = (*jni_env)->GetMethodID(jni_env,audio_track_cls,"write","([BII)I");

   FILE* fp = fopen("/sdcard/temp.pcm","rb");
   LOGI2("after open");
   int i=0;
   while(!feof(fp)){
	   jint read= fread(buf,sizeof(char),200,fp);
	   (*jni_env)->SetByteArrayRegion(jni_env,buffer, 0,read, (jbyte *)buf);

	   (*jni_env)->CallVoidMethod(jni_env,audio_track,method_write,buffer,0,read);
   }

}

编译文件:Android.mk:

 

 

[html] view plain copy print ?
  1. LOCAL_PATH := $(call my-dir)  
  2.   
  3. include $(CLEAR_VARS)  
  4.   
  5. LOCAL_MODULE    :hello-jni  
  6. LOCAL_SRC_FILES :hello-jni.c  
  7. LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog  
  8. include $(BUILD_SHARED_LIBRARY)  
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := hello-jni
LOCAL_SRC_FILES := hello-jni.c
LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog
include $(BUILD_SHARED_LIBRARY)

 

 

 

贴上效果图:

 

例子中的调用思路:   Activity->JNI API ->c    c->JNI API->Activity     

点击"用AudioRecord录音",启动了一条线程,该线程调用native方法startRecord,开始在native层启动录音。在录音的过程中,再将读取到的音频字节数组丢到java层。方法是:->(*jni_env)->CallStaticVoidMethod(jni_env,HelloJniCls, receiveAudioData, read_buff,nread);   然后在Activity中的静态方法 public static void receiveAudioData(byte[] data,int size){
            try {
                bos.write(data);
                bos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

中将数据写到文件.

至于用AudioTrack来播放的流程差不多,就不废话了。

 

非常要注意的是在:

 

startRecord.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){
                    public void run(){

                        initOutputStream();

                        startRecord();
                    }
                }.start();

            }
        });

这里要写个线程,很重要!!!! ,不然会阻塞UI线程的!!!

 

做这个例子是做一个远程会议产品中要用到底层录音,由于项目中开启录音导致界面很卡,所以通过这个例子找到了原因,那就是录音模块没有在一个非UI线程中运行,导致阻塞UI.


转载自:http://blog.csdn.net/liuxiit/article/details/7915513

你可能感兴趣的:(JNI在Android开发中的应用之--用AudioRecord录音,用AudioTrack播放声音.)