@[TOC](文章目录)
# 一、写DownloadAudio下载工具类
```java
import android.annotation.SuppressLint;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* @author : Code23
* @time : 2020/11/5
* @module : DownloadAudio
* @describe :
*/
public class DownloadAudio {
private File file;
public String savePath; // 储存下载文件的路径
private List
private List
public DownloadAudioListener downloadAudioListener;
public DownloadAudio(DownloadAudioListener downloadAudioListener, String savePath, List
this.downloadAudioListener = downloadAudioListener;
this.savePath = savePath;
this.audiolist = audiolist;
audioNamelist.clear();
audioNamelist = getFilesAllName(savePath);//获取本地已下载的文件名
}
/**
*@author : Code23
*@time : 2020/11/12
*@name : isDownloadAudio
*@Parameters : [url, i]
*@describe : 判断是否已经下载过,已经下载的返回路径,没下载的继续下载
*/
public void isDownloadAudio(final String url, final int i) {
if (audioNamelist != null) {
if (audioNamelist.size() > 0) {
for (int t = 0; t < audioNamelist.size(); t++) {
if (audiolist.get(i).equals(audioNamelist.get(t))) {
downloadAudioListener.DownloadSuccess(savePath + "/" + audioNamelist.get(i), i);
break;
} else {
if (t == audiolist.size() - 1) {
OkHttpDownloadAudio(url, i);
}
}
}
} else {
OkHttpDownloadAudio(url, i);
}
} else {
OkHttpDownloadAudio(url, i);
}
}
/**
* @author : Code23
* @time : 2020/11/5
* @name : downloadFile
* @Parameters : [url, name, dowloadpath]
* @describe :下载文件
*/
@SuppressLint("NewApi")
public void OkHttpDownloadAudio(final String url, final int i) {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//请求失败
downloadAudioListener.DownloadFailure("failure", i);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//请求成功
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
byte[] bytes = new byte[1024 * 10];
int length = 0;
file = new File(savePath);
if (!file.exists()) { //文件夹不存在
// 创建文件夹
file.mkdirs();
}
try {
inputStream = response.body().byteStream();
file = new File(savePath, audiolist.get(i));
fileOutputStream = new FileOutputStream(file);
while ((length = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, length);
}
fileOutputStream.flush();
//下载成功
downloadAudioListener.DownloadSuccess(file.getPath(), i);
} catch (Exception e) {
e.printStackTrace();
// 下载失败
downloadAudioListener.DownloadFailure("failure", i);
} finally {
if (inputStream != null) {
inputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
}
});
}
public interface DownloadAudioListener {
void DownloadSuccess(String audiourl, int i);//成功返回
void DownloadFailure(String audiourl, int i);//失败返回
}
/**
* 获取文件夹所有文件名
*
* @param path
* @return
*/
public List
File file = new File(path);
if (!file.exists()) { //文件夹不存在
// 创建文件夹
file.mkdirs();
}
File[] files = file.listFiles();
if (files == null) {//空目录
return null;
}
List
for (int i = 0; i < files.length; i++) {
stringList.add(files[i].getName());
}
return stringList;
}
}
```
# 二、在Activity或者其他地方使用DownloadAudio工具类
代码如下(示例):
```java
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import com.colortu.listening.constant.Urls;
import com.colortu.listening.utils.DownloadAudio;
import com.colortu.listening.utils.string.StringUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author : Code23
* @time : 2020/11/12
* @module : D
* @describe :
*/
public class AudioPlayerActivity extends Activity implements DownloadAudio.DownloadAudioListener{
private MediaPlayer mediaPlayer;
private Handler handler;
private List
private DownloadAudio downloadAudio;
private List
private String[] audionamelist;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
}
private void initView(){
handler = new Handler();
String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Demo";
for (int i = 0; i < demolist.size(); i++) {
audiolist.add(StringUtil.makeMd5(Urls.CDN_URL + demolist.get(i)));//将网络下载url转成md5
}
audionamelist = new String[demolist.size()];
downloadAudio = new DownloadAudio(this, savePath, audiolist);
//将下载的url转成MD5,下载的文件名为MD5。首次进来拿本地下载好的文件名和网络拿下来的数据对比,
//没有的就下载,有的就返回文件路径就行
if(demolist.size()>0){
downloadAudio.isDownloadAudio(Urls.CDN_URL + demolist.get(0), 0);
}
//可以设置加载动画,下载完后调用play()
play();
}
private void play(){
handler.removeCallbacks(playAudioRun);
handler.post(playAudioRun);
}
private int curItem;//自己去拿你的播放哪一个的下标
Runnable playAudioRun = new Runnable() {
@Override
public void run() {
if (audionamelist != null) {
if (audionamelist[curItem] != null) {
if (!audionamelist[curItem].equals("failure") && !audionamelist[curItem].equals("")) {
playAudio(audionamelist[curItem]);//播放本地路径
} else {
playAudio( demolist.get(curItem));//下载失败或者本地找不到路径就网络播放
}
} else {
playAudio(demolist.get(curItem));//下载失败或者本地找不到路径就网络播放
}
} else {
playAudio(demolist.get(curItem));//下载失败或者本地找不到路径就网络播放
}
}
};
private void playAudio(String url) {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(url);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (IOException e) {
e.printStackTrace();
}
if (mediaPlayer == null) {
return;
}
mediaPlayer.setLooping(false);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (mediaPlayer == mp) {
mediaPlayer.start();
}
}
});
mediaPlayer.prepareAsync();
}
@Override
public void DownloadSuccess(String audiourl, int i) {
if (i < demolist.size()) {
audionamelist[i] = audiourl;
i++;
if (i < demolist.size()) {
downloadAudio.isDownloadAudio(demolist.get(i), i);
}
}
}
@Override
public void DownloadFailure(String audiourl, int i) {
if (i < demolist.size()) {
audionamelist[i] = audiourl;
i++;
if (i < demolist.size()) {
downloadAudio.isDownloadAudio(demolist.get(i), i);
}
}
}
}
```
# 三、String转MD5工具类
## 1.StringUtil 类
```java
import android.text.TextUtils;
import java.util.Locale;
import java.util.UUID;
public class StringUtil {
/**
* String转md5
*
* @param source
* @return String
*/
public static String makeMd5(String source) {
return MD5.getStringMD5(source);
}
/**
* 删除字符串中的空白符
*
* @param content
* @return String
*/
public static String removeBlanks(String content) {
if (content == null) {
return null;
}
StringBuilder buff = new StringBuilder();
buff.append(content);
for (int i = buff.length() - 1; i >= 0; i--) {
if (' ' == buff.charAt(i) || ('\n' == buff.charAt(i)) || ('\t' == buff.charAt(i))
|| ('\r' == buff.charAt(i))) {
buff.deleteCharAt(i);
}
}
return buff.toString();
}
/**
* 获取32位uuid
*
* @return
*/
public static String get32UUID() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
public static boolean isEmpty(String input) {
return TextUtils.isEmpty(input);
}
/**
* 生成唯一号
*
* @return
*/
public static String get36UUID() {
UUID uuid = UUID.randomUUID();
String uniqueId = uuid.toString();
return uniqueId;
}
public static final String filterUCS4(String str) {
if (TextUtils.isEmpty(str)) {
return str;
}
if (str.codePointCount(0, str.length()) == str.length()) {
return str;
}
StringBuilder sb = new StringBuilder();
int index = 0;
while (index < str.length()) {
int codePoint = str.codePointAt(index);
index += Character.charCount(codePoint);
if (Character.isSupplementaryCodePoint(codePoint)) {
continue;
}
sb.appendCodePoint(codePoint);
}
return sb.toString();
}
/**
* counter ASCII character as one, otherwise two
*
* @param str
* @return count
*/
public static int counterChars(String str) {
// return
if (TextUtils.isEmpty(str)) {
return 0;
}
int count = 0;
for (int i = 0; i < str.length(); i++) {
int tmp = (int) str.charAt(i);
if (tmp > 0 && tmp < 127) {
count += 1;
} else {
count += 2;
}
}
return count;
}
}
```
## 2.MD5 类
```java
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
public class MD5 {
public static String getStringMD5(String value) {
if (value == null || value.trim().length() < 1) {
return null;
}
try {
return getMD5(value.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public static String getMD5(byte[] source) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
return HexDump.toHex(md5.digest(source));
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public static String getStreamMD5(String filePath) {
String hash = null;
byte[] buffer = new byte[4096];
BufferedInputStream in = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
in = new BufferedInputStream(new FileInputStream(filePath));
int numRead = 0;
while ((numRead = in.read(buffer)) > 0) {
md5.update(buffer, 0, numRead);
}
in.close();
hash = HexDump.toHex(md5.digest());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return hash;
}
}
```
## 3.HexDump 类
```java
import java.io.IOException;
import java.io.StringReader;
public class HexDump {
class HexTablifier {
private int m_row = 8;
private String m_pre = "";
private String m_post = "\n";
public HexTablifier() {
}
public HexTablifier(int row) {
this(row, "", "\n");
}
public HexTablifier(int row, String pre) {
this(row, pre, "\n");
}
public HexTablifier(int row, String pre, String post) {
m_row = row;
m_pre = pre;
m_post = post;
}
public String format(String hex) {
StringReader reader = new StringReader(hex);
StringBuilder builder = new StringBuilder(hex.length() * 2);
try {
while (getHexLine(builder, reader)) {
}
} catch (IOException e) {
// 不应该有异常出现。
}
return builder.toString();
}
private boolean getHexLine(StringBuilder builder, StringReader reader)
throws IOException {
StringBuilder lineBuilder = new StringBuilder();
boolean result = true;
for (int i = 0; i < m_row; i++) {
result = getHexByte(lineBuilder, reader);
if (result == false)
break;
}
if (lineBuilder.length() > 0) {
builder.append(m_pre);
builder.append(lineBuilder);
builder.append(m_post);
}
return result;
}
private boolean getHexByte(StringBuilder builder, StringReader reader)
throws IOException {
char[] hexByte = new char[4];
int bytesRead = reader.read(hexByte);
if (bytesRead == -1)
return false;
builder.append(hexByte, 0, bytesRead);
builder.append(" ");
return bytesRead == 4;
}
}
private static final char m_hexCodes[] = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static final int m_shifts[] = {60, 56, 52, 48, 44, 40, 36, 32, 28,
24, 20, 16, 12, 8, 4, 0};
public static String tablify(byte[] bytes) {
return (new HexDump()).new HexTablifier().format(HexDump.toHex(bytes));
}
public static String tablify(byte[] bytes, int row) {
return (new HexDump()).new HexTablifier(row).format(HexDump
.toHex(bytes));
}
public static String tablify(byte[] bytes, int row, String pre) {
return (new HexDump()).new HexTablifier(row, pre).format(HexDump
.toHex(bytes));
}
public static String tablify(String hex, int row, String pre, String post) {
return (new HexDump()).new HexTablifier(row, pre, post).format(hex);
}
private static String toHex(final long value, final int digitNum) {
StringBuilder result = new StringBuilder(digitNum);
for (int j = 0; j < digitNum; j++) {
int index = (int) ((value >> m_shifts[j + (16 - digitNum)]) & 15);
result.append(m_hexCodes[index]);
}
return result.toString();
}
public static String toHex(final byte value) {
return toHex(value, 2);
}
public static String toHex(final short value) {
return toHex(value, 4);
}
public static String toHex(final int value) {
return toHex(value, 8);
}
public static String toHex(final long value) {
return toHex(value, 16);
}
public static String toHex(final byte[] value) {
return toHex(value, 0, value.length);
}
public static String toHex(final byte[] value, final int offset,
final int length) {
StringBuilder retVal = new StringBuilder();
int end = offset + length;
for (int x = offset; x < end; x++)
retVal.append(toHex(value[x]));
return retVal.toString();
}
public static byte[] restoreBytes(String hex) {
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; ++i) {
int c1 = charToNumber(hex.charAt(2 * i));
int c2 = charToNumber(hex.charAt(2 * i + 1));
if (c1 == -1 || c2 == -1) {
return null;
}
bytes[i] = (byte) ((c1 << 4) + c2);
}
return bytes;
}
private static int charToNumber(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 0xa;
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 0xA;
} else {
return -1;
}
}
}
```
# 总结
本文章只是提供一个思路,需要改进和完善的自己去研究研究。