Android录音播放工具类,仿微信语音聊天。

时间:2021-10-27 16:08:19

代码是从聊天类项目中抽出来的,播放类中含有本地播放和网络播放,做法仿微信,先将网络路径中的.amr文件下载下来,然后存到本地播放。
一、录音类

import java.io.File;
import java.io.IOException;

import android.media.MediaRecorder;

public class ChatRecorder {

private String mOutputFileName = "";
private MediaRecorder mRecorder = null;
private long mStartTime = 0L;
private static ChatRecorder mChatRecorder = null;

private ChatRecorder() {}

public static ChatRecorder getInstance() {
if (mChatRecorder == null) {
synchronized (ChatRecorder.class) {
if (mChatRecorder == null) {
mChatRecorder = new ChatRecorder();
}
}
}
return mChatRecorder;
}

public void initRecorder() {
mRecorder = new MediaRecorder();
}

public void startRecord(String outputFileName) {
if (mRecorder == null) {
return;
}
this.mOutputFileName = outputFileName;
File parentFile = new File(outputFileName).getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setOutputFile(mOutputFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mRecorder.start();
mStartTime = System.currentTimeMillis();
}


public long stopRecord() {
if (mRecorder != null) {
mRecorder.stop();
return System.currentTimeMillis() - mStartTime;
}
return 0L;
}

public void exitRecorder() {
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
}

public String getOutputFileName() {
return mOutputFileName;
}

public double getAmplitude() {
if (mRecorder != null) {
return (mRecorder.getMaxAmplitude() / 2700.0);
} else {
return 0;
}
}
}

二、播放类

package net.bangbao.im.imkit.base;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import net.bangbao.R;
import net.bangbao.XConfig;
import net.bangbao.XManager;
import net.bangbao.utils.EncryptionUtils;
import net.bangbao.utils.FileUtil;
import net.bangbao.utils.UIUtils;
import net.bangbao.utils.Utils;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;

public class ChatPlayer {
private static final String TAG = ChatPlayer.class.getSimpleName();
private static final int MSG_WHAT_PLAY = 1000;
private static ChatPlayer mChatPlayer = null;
private MediaPlayer mPlayer = null;
private String mCurrentUrl = "";
private OnMediaPlayListener mMediaPlayListener = null;
private Handler mHandler = null;
Callback downloadCallback = new Callback() {

@Override
public boolean handleMessage(Message msg) {
if (msg.what == MSG_WHAT_PLAY) {
if (msg.obj instanceof File) {
File localFile = (File) msg.obj;
playFromLocal(localFile);
}
}
return false;
}
};

private ChatPlayer() {}

public static ChatPlayer getInstance() {
if (mChatPlayer == null) {
synchronized (ChatPlayer.class) {
if (mChatPlayer == null) {
mChatPlayer = new ChatPlayer();
}
}
}
return mChatPlayer;
}

public interface OnMediaPlayListener {

void onStart(String url);

void onCompletion(String url);

void onError(String url);
}

public void init() {
mPlayer = new MediaPlayer();
mHandler = new Handler(downloadCallback);
}

public void play(final String url, final OnMediaPlayListener listener) {
if (mPlayer == null) {
return;
}
if (mPlayer.isPlaying()) {
mPlayer.stop();
if (mMediaPlayListener != null) {
mMediaPlayListener.onCompletion(mCurrentUrl);
}
}
mCurrentUrl = url;
mMediaPlayListener = listener;
mPlayer.setOnCompletionListener(new OnCompletionListener() {

@Override
public void onCompletion(MediaPlayer mp) {
if (mMediaPlayListener != null) {
mMediaPlayListener.onCompletion(mCurrentUrl);
}
}
});

mPlayer.setOnErrorListener(new OnErrorListener() {

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (mMediaPlayListener != null) {
listener.onError(mCurrentUrl);
}
return false;
}
});

if (!FileUtil.isCanUseSDCard()) {
UIUtils.toastMsgFromResource(XManager.getManager().getApplication(), R.string.sdcard_err);
return;
}

String wholeUrl = Utils.getWholeUrl(mCurrentUrl, XConfig.FILE_SCHEME);
if (wholeUrl.startsWith(XConfig.FILE_SCHEME)) {
playFromLocal(wholeUrl);
return;
}

File localDir = new File(XConfig.DIR_CHAT_VOICE_CACHE);
if (!localDir.exists()) {
localDir.mkdirs();
}
final File localFile = new File(localDir, mCurrentUrl + ".amr");
if (localFile.exists()) {
playFromLocal(localFile);
} else {
playFromNetwork(mCurrentUrl, localFile);
}
}

public boolean isPlaying() {
if (mPlayer == null) {
return false;
}
return mPlayer.isPlaying();
}

public void stop() {
if (mPlayer != null) {
mPlayer.stop();
if (mMediaPlayListener != null) {
mMediaPlayListener.onCompletion(mCurrentUrl);
}
}
}

public void release() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
mHandler.removeMessages(MSG_WHAT_PLAY);
if (mMediaPlayListener != null) {
mMediaPlayListener.onCompletion(mCurrentUrl);
}
}
}

private void playFromNetwork(final String source, final File localFile) {
new Thread(new Runnable() {

@Override
public void run() {
int count;
try {
URL url = new URL(source);
URLConnection conn = url.openConnection();
conn.connect();

InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(localFile);

byte data[] = new byte[1024];

while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
Message msg = mHandler.obtainMessage();
msg.what = MSG_WHAT_PLAY;
msg.obj = localFile;
mHandler.sendMessage(msg);

}
}).start();
}

private void playFromLocal(File localFile) {
if (mPlayer == null) {
return;
}
try {
Uri uri = Uri.fromFile(localFile);
mPlayer.reset();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(XManager.getManager().getApplication(), uri);
mPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mPlayer.start();
if (mMediaPlayListener != null) {
mMediaPlayListener.onStart(mCurrentUrl);
}
}

private void playFromLocal(String localFilePath) {
if (mPlayer == null) {
return;
}
try {
mPlayer.reset();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(localFilePath);
mPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mPlayer.start();
if (mMediaPlayListener != null) {
mMediaPlayListener.onStart(mCurrentUrl);
}
}
}