一、交叉编译LAME库
LAME是一种非常优秀的MP3编码引擎,在业界,转码成MP3格式的音频文件时,最常用的编码器就是LAME库。
1. 下载LAME库源码
https://sourceforge.net/projects/lame/files/lame/
进入LAME官网下载LAME源码,我选择最新版本:3.100
2. 配置交叉编译环境
在编译LAME之前,我们需要先配置交叉编译环境。
Android NDK附带了交叉工具链,具体参考这篇文章:https://developer.android.com/ndk/guides/other_build_systems?hl=zh-cn
我的NDK路径为:/home/lorien/Android/Sdk/ndk/22.1.7171670/toolchains/llvm/prebuilt/linux-x86_64/bin
3. 配置、编译、安装LAME
首先我们需要编译使用的一些环境变量:
#!/bin/bash
export TOOLCHAIN=/home/lorien/Android/Sdk/ndk/22.1.7171670/toolchains/llvm/prebuilt/linux-x86_64
export TARGET=aarch64-linux-android
export API=21
export AR=$TOOLCHAIN/bin/llvm-ar
export CC=$TOOLCHAIN/bin/$TARGET$API-clang
export AS=$CC
export CXX=$TOOLCHAIN/bin/$TARGET$API-clang++
export LD=$TOOLCHAIN/bin/ld
export RANLIB=$TOOLCHAIN/bin/llvm-ranlib
export STRIP=$TOOLCHAIN/bin/llvm-strip
export CFLAGS="-fPIC"
接下来解压的LAME源码:lame-3.100.tar.gz,解压后进入源码根目录:/lame-3.100
配置:
./configure --host=arm-linux --disable-shared --disable-frontend --enable-static --prefix=/Users/zhanghao43/Desktop/lame/arm64-v8a
编译:
make clean
make -j4
安装:
make install
安装完成后,生成的头文件和库文件,就会在prefix指定的路径下面,即:/Users/zhanghao43/Desktop/lame/arm64-v8a
在生成的文件中,接下来需要使用的文件是:
- 头文件:/Users/zhanghao43/Desktop/lame/arm64-v8a/include/lame/lame.h
- 库文件:/Users/zhanghao43/Desktop/lame/arm64-v8a/lib/lame/libmp3lame.a
至此,LAME库交叉编译完成。
二、创建Android Native项目使用LAME库
下面我们使用LAME库创建一个Android Demo项目,完成PCM音频的录制以及PCM文件转MP3的功能
我们需要创建Android Natvie项目。
1. 配置工程
我们先把编译LAME库生成的头文件和库文件放到项目中,路径如下图:

然后,我们修改下CMakeLists.txt,让CMake在编译、链接时,找到LAME头文件和库文件。CMakeLists.txt文件内容如下:
cmake_minimum_required(VERSION 3.10.2)
# Declares and names the project.
project("lame")
include_directories(
${CMAKE_SOURCE_DIR}/include/lame)
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
native-lib.cpp mp3_encoder.cpp)
add_library(mp3lame STATIC IMPORTED)
set_target_properties(mp3lame PROPERTIES IMPORTED_LOCATION
${CMAKE_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libmp3lame.a)
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
target_link_libraries(native-lib
mp3lame)
2. C++代码
接下来,可以写代码了。首先看一下mp3_encoder.h, mp3_encoder.cpp
#ifndef LAME_MP3ENCODER_H
#define LAME_MP3ENCODER_H
#include <stdio.h>
#include "lame.h"
class Mp3Encoder {
private:
FILE* pcmFile;
FILE* mp3File;
lame_t lameClient;
public:
Mp3Encoder();
~Mp3Encoder();
int Init(const char* pcmFilePath, const char* mp3FilePath, int sampleRate, int channels, int bitRate);
void Encode();
void Destroy();
};
#endif //LAME_MP3ENCODER_H
#include "mp3_encoder.h"
#include "lame.h"
Mp3Encoder::Mp3Encoder()


2070

被折叠的 条评论
为什么被折叠?



