Android JNI Lame codec for conversion from WAV to MP3

Source: Internet
Author: User

1. Introduction to JNI
JNI is all called Java Native Interface (Java Local call). Starting with Java1.1, JNI becomes part of the Java platform, which allows Java code to interact with code written in other languages, such as c&c++. The concept of JNI was not introduced from Android.
2. Jni and NDK
In short, the Android NDK offers a number of cross-compilation toolchain and Android-brought libraries that allow developers to invoke programs in their native languages. The cross-compilation toolchain provided by the NDK compiles the c&c++ code that has been written, creating a library.
Of course, you can also build your own cross-compilation environment without the NDK tools and libraries. The library is then generated, as long as the canonical operation can generate a library file that allows the Java layer to be successfully called.

    使用JNI技术,其实就是在Java程序中,调用C语言的函数库中提供的函数,来完成一些Java语言无法完成的任务。由于Java语言和C语言结构完全不相同,因此若想让它们二者交互,则需要制定一系列的规范。JNI就是这组规范,此时    Java只和JNI交互,而由JNI去和C语言交互。

JNI technology is divided into two parts: Java side and C language side. And is dominated by the Java side.
|-First, Java programmers define some native methods on the Java side and provide these methods to C programmers in the form of a C-language header file.
|-Then, c programmers use the C language to implement functions defined in the header files provided by the Java programmer.
|-Next, the C programmer packages the function into a library file and gives the library file to the Java programmer.

When the Java program executes, if the native method is called in a class, the virtual opportunity passes through JNI to invoke the C language code in the library file. Tip: The C code is ultimately executed in the Linux process, not in the virtual machine.

The following is an Android call JNI implementation that implements the conversion of WAV format to MP3 format via the lame transcoding device.

Preparation: First download lame source files.
Three conditions are required: CGYWIN,CDT,NDK to achieve JNI development.
Development lame need to select the using lame from http://lame.sourceforge.net/to download the source code.

New Project
1. Android Main interface layout

<?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" >                <EditTextandroid:id="@+id/edittext1"android:hint="path of the source WAV file"  Android:text="/sdcard/118/ccc.wav"android:layout_width="Match_parent" android:layout_height="Wrap_content" >                                            </EditText>    <edittext  android:id  = "@+id/edittext2"  android:hint  =< Span class= "Hljs-value" > "destination MP3 file path"  android:layout_width  = "match_parent"  android:text  ="/sdcard/118/ccccc.mp3 " android:layout_height  =" wrap_content "/>     <button  android:id  = "@+id/button1"  android:layout_width  = "wrap_content"  android:layout_height  = "wrap_content"  android:text  =" conversion " android:onclick  =" Convert " /span>/>     <buttonandroid:id="@+id/button2"android:layout_width="Wrap_ Content "android:layout_height=" Wrap_content "android:text=" Get Lame version number " Android:onclick="getversion" />                                        </linearlayout>

The first is to create a JNI directory

1, the Lamec language source code into the JNI
2. Create a android.mk file

Local_path: = $ (PagerMY-DIR) include $ (clear_vars) Local_module: = hellolocal_src_files: = bitstream. CFft. CId3tag. CMpglib_interface. CPresets. CQuantize. CReservoir. CTables. CUtil. CVbrtag. CEncoder. CGain_analysis. CLame. CNewmdct. CPsymodel. CQuantize_pvt. CSet_get. CTakehiro. CVbrquantize. CVersion. CHello. CLocal_ldlibs + =-lloginclude $ (build_shared_library)

3. Writing C language files

#include <stdio.h>#include <jni.h>#include "com_example_ndkpassdata_dataprovider.h"#include <android/log.h>#include <malloc.h>#define LOG_TAG "system.out.c"#define LOGD (...) __android_log_print (android_log_debug,log_tag,__va_args__)#define Logi (...) __android_log_print (android_log_info,log_tag,__va_args__)char* Jstring2cstr (jnienv* env, jstring jstr) {char* RTN = NULL; Jclass clsstring = (*env)Findclass (ENV,"Java/lang/string");//String jstring Strencode = (*env)Newstringutf (ENV,"GB2312");//Get a Java string"GB2312"Jmethodid Mid = (*env)Getmethodid (env, clsstring,"GetBytes","(ljava/lang/string;) [B]);//[String.getbytes ("gb2312"); Jbytearray Barr = (Jbytearray) (*env),Callobjectmethod (env, JSTR, Mid, Strencode);//String. GetByte ("GB2312"); Jsize Alen = (*env)Getarraylength (env, Barr);//The length of the byte array jbyte* ba = (*env)Getbytearrayelements (env, Barr, Jni_false);if(Alen >0) {Rtn = (char*) malloc (Alen +1);//" the"memcpy (RTN, BA, Alen); Rtn[alen] =0; } (*env)Releasebytearrayelements (env, Barr, BA,0);//    returnRTN;}    Jniexport jint jnicall java_com_example_ndkpassdata_dataprovider_add (jnienv *env, Jobject obj, Jint x, Jint y) { LOGD ("x=%d", x); LOGD ("y=%d", y);returnx + y;} Jniexport jstring jnicall java_com_example_ndkpassdata_dataprovider_sayhelloinc (JNIEnv *env, Jobject obj, jstring    JSTR) {Char *cstr = JSTRING2CSTR (env, JSTR); LOGD ("cstr=%s", CStr); Char arr[7] = {"',' h ',' E ',' l ',' l ',' O ','/0 '};    strcat (CStr, arr); LOGD ("newcstr=%s", CStr);return  (*env)Newstringutf (env, CSTR);} Jniexport jintarray jnicall Java_com_example_ndkpassdata_dataprovider_intmethod (JNIEnv *env, Jobject obj, JintArra Y arr) {int len = (*env)Getarraylength (env, arr); LOGD ("Shuzu length-=%d", Len); Jint * Intarr = (*env)Getintarrayelements (env, arr,1); int i =0; for(; i < Len; i++) {LOGD ("intarr[%d]=%d", I, intarr[i]); * (Intarr + i) + =Ten;//iNtarr[i] + =Ten; } (*env)Releaseintarrayelements (env, arr, intarr, Len);returnarr;}    Jniexport jint jnicall java_com_example_ndkpassdata_dataprovider_sub (jnienv *env, Jclass clazz, Jint x, Jint y) { LOGD ("x=%d", x); LOGD ("y=%d", y);returnX-y;}

4. Using Cgywin tool to compile Ndk-build
After success
5. Writing Activity files

 PackageCn.itcast.lame;ImportJava.io.File;Importandroid.app.Activity;ImportAndroid.app.ProgressDialog;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast; Public  class lameactivity extends Activity {    PrivateEditText et_wav;PrivateEditText Et_mp3;PrivateProgressDialog PD; Public native void Convertmp3(String wav,string mp3); Public nativeStringgetlameversion(); Public native void Stop();Static{System.loadlibrary ("Hello"); }@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.main); Et_wav = (EditText) This. Findviewbyid (R.ID.EDITTEXT1); Et_mp3 = (EditText) This. Findviewbyid (R.ID.EDITTEXT2); PD =NewProgressDialog ( This); } Public void Convert(View view) {FinalString mp3name = Et_mp3.gettext (). toString (). Trim ();FinalString wavname = Et_wav.gettext (). toString (). Trim (); File File =NewFile (Wavname);intSize = (int) File.length (); System.out.println ("File Size"+ size);if("". Equals (mp3name) | |"". Equals (Wavname)) {Toast.maketext ( This,"Path cannot be empty",1). Show ();return; }//convertmp3 (wavname,mp3name);Pd.setmessage ("in transition ....");        Pd.setprogressstyle (progressdialog.style_horizontal); Pd.setmax (size);//Set the maximum value of the progress bar        //pd.setcancelable (false);Pd.show ();NewThread () {@Override             Public void Run() {Convertmp3 (wavname,mp3name);            Pd.dismiss ();    }}.start (); } Public void setconvertprogress(intProgress) {pd.setprogress (progress); } Public void getversion(View view)        {String Version = Getlameversion (); Toast.maketext ( This, version,0). Show (); }}

6. Running the program

Source Address:
http://download.csdn.net/detail/kai46385076/8999373

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android JNI Lame codec for conversion from WAV to MP3

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.