首页 > 系统 > Android > 正文

Android录音播放管理工具

2019-12-12 03:54:33
字体:
来源:转载
供稿:网友

1、语音播放直接用系统工具就好了,这个就不多说了,根据传入的路径(网络路径或本地路径均可)播放音频文件

/** * Created by zhb on 2017/1/16. * 音乐在线播放 */public class PlayManager { private Context mcontext; public PlayManager(Context context){  this.mcontext = context; } public void play(String song){  MediaPlayer mp = new MediaPlayer();  try {//   存储在SD卡或其他文件路径下的媒体文件//   例如:mp.setDataSource("/sdcard/test.mp3");//   网络上的媒体文件//   例如:mp.setDataSource("http://www...../music/test.mp3");   mp.setDataSource(song);   mp.prepare();   mp.start();  } catch (Exception e) {   e.printStackTrace();  } }}

2.录制amr格式音频文件(微信语音便用的这种格式,至于音频文件格式之间的比较请自行百度)

/** * Created by zhb on 2017/1/16. * 本地录音 */public class RecordManager { //录制成amr格式............................................................ private Context mcontext; MediaRecorder mediaRecorder ; public RecordManager(Context context){  this.mcontext = context;  //TODO 初始化安装路径,录音流程 } /**开始录制*/ public void start_amr(){  mediaRecorder = new MediaRecorder();  /**   * mediaRecorder.setAudioSource设置声音来源。   * MediaRecorder.AudioSource这个内部类详细的介绍了声音来源。   * 该类中有许多音频来源,不过最主要使用的还是手机上的麦克风,MediaRecorder.AudioSource.MIC   */  mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);  /**   * mediaRecorder.setOutputFormat代表输出文件的格式。该语句必须在setAudioSource之后,在prepare之前。   * OutputFormat内部类,定义了音频输出的格式,主要包含MPEG_4、THREE_GPP、RAW_AMR……等。   */  mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);  /**   * mediaRecorder.setAddioEncoder()方法可以设置音频的编码   * AudioEncoder内部类详细定义了两种编码:AudioEncoder.DEFAULT、AudioEncoder.AMR_NB   */  mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);  /**   * 设置录音之后,保存音频文件的位置,一般是SD卡的位置   */  mediaRecorder.setOutputFile(String.valueOf(PathManger.getVoicePath()));  /**   * 调用start开始录音之前,一定要调用prepare方法。   */  try {   mediaRecorder.prepare();   mediaRecorder.start();  }  catch (IllegalStateException e) {   e.printStackTrace();  }  catch (IOException e) {   e.printStackTrace();  } } /**停止录音*/ public void stop_amr(){  mediaRecorder.stop();  mediaRecorder.release();  mediaRecorder = null; } /**重置录音*/ public void reset_amr(){  mediaRecorder.reset(); }}

3、配置转换工具包(这个比较简单,配置以下文件即可)

添加flame.jar,并在armeabi和armeabi-v7a文件夹添加libmp3lame.so
资源文件:http://xiazai.VeVB.COm/201701/yuanma/androidlibmp3lame(VeVB.COm).rar

4、录制MP3格式音频文件(个人觉得这种格式能比较好的统一Android端和iOS端的音频文件,虽然方法相对比较繁杂一些)

/** * Created by zhb on 2017/1/16. * 本地录音 */public class RecordManager { //录制成MP3格式.............................................. /**构造时候需要的Activity,主要用于获取文件夹的路径*/ private Activity activity; /**文件代号*/ public static final int RAW = 0X00000001; public static final int MP3 = 0X00000002; /**文件路径*/ private String rawPath = null; private String mp3Path = null; /**采样频率*/ private static final int SAMPLE_RATE = 11025; /**录音需要的一些变量*/ private short[] mBuffer; private AudioRecord mRecorder; /**录音状态*/ private boolean isRecording = false; /**是否转换ok*/ private boolean convertOk = false; public RecordManager(Activity activity, String rawPath, String mp3Path) {  this.activity = activity;  this.rawPath = rawPath;  this.mp3Path = mp3Path; } /**开始录音*/ public boolean start_mp3() {  // 如果正在录音,则返回  if (isRecording) {   return isRecording;  }  // 初始化  if (mRecorder == null) {   initRecorder();  }  getFilePath();  mRecorder.startRecording();  startBufferedWrite(new File(rawPath));  isRecording = true;  return isRecording; } /**停止录音,并且转换文件,这很可能是个耗时操作,建议在后台中做*/ public boolean stop_mp3() {  if (!isRecording) {   return isRecording;  }  // 停止  mRecorder.stop();  isRecording = false;//TODO  // 开始转换  FLameUtils lameUtils = new FLameUtils(1, SAMPLE_RATE, 96);  convertOk = lameUtils.raw2mp3(rawPath, mp3Path);  return isRecording ^ convertOk;// convertOk==true,return true } /**获取文件的路径*/ public String getFilePath(int fileAlias) {  if (fileAlias == RAW) {   return rawPath;  } else if (fileAlias == MP3) {   return mp3Path;  } else   return null; } /**清理文件*/ public void cleanFile(int cleanFlag) {  File f = null;  try {   switch (cleanFlag) {    case MP3:     f = new File(mp3Path);     if (f.exists())      f.delete();     break;    case RAW:     f = new File(rawPath);     if (f.exists())      f.delete();     break;    case RAW | MP3:     f = new File(rawPath);     if (f.exists())      f.delete();     f = new File(mp3Path);     if (f.exists())      f.delete();     break;   }   f = null;  } catch (Exception e) {   e.printStackTrace();  } } /**关闭,可以先调用cleanFile来清理文件*/ public void close() {  if (mRecorder != null)   mRecorder.release();  activity = null; } /**初始化*/ private void initRecorder() {  int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE,    AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);  mBuffer = new short[bufferSize];  mRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE,    AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,    bufferSize); } /**设置路径,第一个为raw文件,第二个为mp3文件*/ private void getFilePath() {  try {   String folder = "audio_recorder_2_mp3";   String fileName = String.valueOf(System.currentTimeMillis());   if (rawPath == null) {    File raw = new File(activity.getDir(folder,      activity.MODE_PRIVATE), fileName + ".raw");    raw.createNewFile();    rawPath = raw.getAbsolutePath();    raw = null;   }   if (mp3Path == null) {    File mp3 = new File(activity.getDir(folder,      activity.MODE_PRIVATE), fileName + ".mp3");    mp3.createNewFile();    mp3Path = mp3.getAbsolutePath();    mp3 = null;   }   Log.d("rawPath", rawPath);   Log.d("mp3Path", mp3Path);   runCommand("chmod 777 " + rawPath);   runCommand("chmod 777 " + mp3Path);  } catch (Exception e) {   e.printStackTrace();  } } /**执行cmd命令,并等待结果*/ private boolean runCommand(String command) {  boolean ret = false;  Process process = null;  try {   process = Runtime.getRuntime().exec(command);   process.waitFor();   ret = true;  } catch (Exception e) {   e.printStackTrace();  } finally {   try {    process.destroy();   } catch (Exception e) {    e.printStackTrace();   }  }  return ret; } /**写入到raw文件*/ private void startBufferedWrite(final File file) {  new Thread(new Runnable() {   @Override   public void run() {    DataOutputStream output = null;    try {     output = new DataOutputStream(new BufferedOutputStream(       new FileOutputStream(file)));     while (isRecording) {      int readSize = mRecorder.read(mBuffer, 0,        mBuffer.length);      for (int i = 0; i < readSize; i++) {       output.writeShort(mBuffer[i]);      }     }    } catch (IOException e) {     e.printStackTrace();    } finally {     if (output != null) {      try {       output.flush();      } catch (IOException e) {       e.printStackTrace();      } finally {       try {        output.close();       } catch (IOException e) {        e.printStackTrace();       }      }     }    }   }  }).start(); }}

5、最后在自己想调用的地方调用就好了,PathManger这个是我自己的路径管理工具,这里不贴了,反正自己直接放一个路径字符串进去就好了

/**初始化语音*/ private void initVoice() { //录音 RecordManager = new RecordManager(  CallHelpActivity.this,  String.valueOf(PathManger.getVoicePathToRaw()),  String.valueOf(PathManger.getVoicePathToMp3())); callHelp_Voice_longclick.setOnTouchListener(new View.OnTouchListener() {  @Override  public boolean onTouch(View v, MotionEvent event) {  switch(event.getAction()){   case MotionEvent.ACTION_DOWN:   RecordManager.start_mp3();   break;   case MotionEvent.ACTION_MOVE:   break;   case MotionEvent.ACTION_UP:   RecordManager.stop_mp3();   break;  }  return false;  } }); //语音播放 final PlayManager PlayManager = new PlayManager(this); callHelp_Voice_click.setOnClickListener(new View.OnClickListener() {  @Override  public void onClick(View v) {  PlayManager.play(String.valueOf(PathManger.getVoicePathToMp3()));  } }); }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表