deepak jha | Techbirds | Page 2

Continuing my previous blog on how to install NDK and compile and Prepare Lame Library. I am sharing an example on how to use Native code in your java/ android code. This example convert raw/pcm File to Mp3 file.

Activity which loads Native Library (Mp3Lame)

public class MyLameClass extends Activity {

static {System.loadLibrary(“mp3lame”);}

//declare Native method which is to be called.

private native int encodeFile(String sourcePath, String targetPath);

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.activity_lame);

// native method called with source and destination path

encodeFile(“mnt/sdcard/xyz.pcm” , “mnt/sdcard/abc.mp3);

}

Native code with Method called from Activity Class

Wrapper.c

#include #include #include #include

#include “libmp3lame/lame.h”

// method which Encode Raw/pcm data in MP3 format.

void Java_com_samsung_sample_lame4android_LameActivity_encodeFile(JNIEnv *env, jobject jobj, jstring in_source_path, jstring in_target_path) { const char *source_path, *target_path; source_path = (*env)->GetStringUTFChars(env, in_source_path, NULL);

target_path = (*env)->GetStringUTFChars(env, in_target_path, NULL);

FILE *input_file, *output_file; input_file = fopen(source_path, “rb”);

output_file = fopen(target_path, “wb”);

short input[BUFFER_SIZE]; char output[BUFFER_SIZE]; int nb_read = 0; int nb_write = 0;

int nb_total = 0;

LOGD(“Encoding started”);
while (nb_read = read_samples(input_file, input)) {

nb_write = lame_encode_buffer(lame, input, input, nb_read, output, BUFFER_SIZE); fwrite(output, nb_write, 1, output_file); nb_total += nb_write; }

LOGD(“Encoded %d bytes”, nb_total);

nb_write = lame_encode_flush(lame, output, BUFFER_SIZE); fwrite(output, nb_write, 1, output_file);

LOGD(“Flushed %d bytes”, nb_write);

fclose(input_file); fclose(output_file);

}

606 total views, 2 views today