一.将前台传来的serverId(mediaId)拿来,用于请求微信接口,获取amr文件,并将amr文件保存在相关路径作为临时文件,具体代码如下:
public static String downloadMediaId(HttpServletRequest request, String mediaId) {
InputStream inputStream = getInputStream(mediaId);
FileOutputStream fileOutputStream = null;
//服务器资源保存路径
String savePath = "/data/web/uploadfiles/temp/";//你文件的保存路径
String filename = String.valueOf(System.currentTimeMillis()) + ".amr";//文件名
try {
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
byte[] data = new byte[1024];
int len = 0;
fileOutputStream = new FileOutputStream(savePath + filename);
while ((len = inputStream.read(data)) != -1) {
// 判断结果是否有错
if (new String(data).indexOf("errmsg") > -1) {
return null;
//return ;
}
fileOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return savePath+filename;
}
public static InputStream getInputStream(String mediaId) {
InputStream is = null;
try {
String access_token = WeChatUtil.getAccessToken(MemberController.miniProAppId, MemberController.miniProAppSecret, 0);
String URL_DOWNLOAD_TEMP_MEDIA = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
String url = URL_DOWNLOAD_TEMP_MEDIA.replace("ACCESS_TOKEN", access_token).replace("MEDIA_ID", mediaId);
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
// 获取文件转化为byte流
is = http.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return is;
}
该方法返回保存的amr文件的路径
二.将amr文件转为mp3文件,具体如下:
(1).添加环境:
maven项目添加依赖:
<!--amr文件转音频map文件-->
<dependency>
<groupId>com.github.dadiyang</groupId>
<artifactId>jave</artifactId>
<version>1.0.3</version>
</dependency>
jar包:
链接:https://pan.baidu.com/s/1YgXbpkxmFbJCupBu2UF61w
提取码:8sev
(2)具体代码如下:
/**
* 将微信语音文件保存
* @param serverId
* @throws IOException
*/
@RequestMapping(value="/insertWxVoice")
@ResponseBody
public Object insertWxVoice(@RequestParam("serverId") String serverId,HttpServletRequest request) throws IOException{
Map<String,Object> returnMap = new HashMap<>();
String YearMonthDay = DateUtil.dateFormat(new Date(), "yyyyMMdd");
String sourcePath = WeChatUtil.downloadMediaId(request,serverId);
if(sourcePath==null){
return AppUtil.returnObject(returnMap,Const.ERRORCODE);
}
String targetPath = "/data/web/uploadfiles/voice/"+YearMonthDay+"/"+String.valueOf(System.currentTimeMillis()) + ".mp3";
File temp = new File("/data/web/uploadfiles/voice/"+YearMonthDay+"/");
if(!temp.exists()){//如果文件夹不存在
temp.mkdir();//创建文件夹
}
File source = new File(sourcePath);//源文件
File target = new File(targetPath);//目标文件
if(!source.exists()){
source.createNewFile();
}
if(!target.exists()){
target.createNewFile();
}
//AudioUtils.amrToMp3(source, target);
changeToMp3(sourcePath, targetPath);
returnMap.put("filename", targetPath);
return AppUtil.returnObject(returnMap,Const.SUCCESSCODE);
}
public static void changeToMp3(String sourcePath, String targetPath) {
File source = new File(sourcePath);
File target = new File(targetPath);
AudioAttributes audio = new AudioAttributes();
Encoder encoder = new Encoder(new MyFFMpegLoader());
audio.setCodec("libmp3lame");
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat("mp3");
attrs.setAudioAttributes(audio);
try {
encoder.encode(source, target, attrs);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InputFormatException e) {
e.printStackTrace();
} catch (EncoderException e) {
e.printStackTrace();
}
}
public class MyFFMpegLoader extends FFMPEGLocator{
@Override
protected String getFFMPEGExecutablePath() {
return "/data/soft/ffmpeg/ffmpeg"; //ffmpeg地址
}
}
基本流程就是这样
三.在开发流程中,虽然代码很快写完,并且在Windows能很快实现,但是在Linux就遇到了种种问题,现在一一例举:
(1).java.lang.ClassNotFoundException: it.sauronsoftware.jave.AudioUtils
这个错误是因为环境问题,jar包报错位置了
(2)Linux it.sauronsoftware.jave.EncoderException: Duration: N/A, bitrate: N/A
这个在Windows和Linux都会有,但是Windows他能生成mp3文件,并且不为0kb,,二Linux系统是0kb
解决方法:
引入类:
public class MyFFMpegLoader extends FFMPEGLocator{
@Override
protected String getFFMPEGExecutablePath() {
return "/data/soft/ffmpeg/ffmpeg"; //ffmpeg地址
}
}
自定义修改ffmpeg地址,是其在Linux系统能够被找到
在changeToMp3()方法中将
Encoder encoder = new Encoder();
改为
Encoder encoder = new Encoder(new MyFFMpegLoader());
(3).改成之后,但还是有问题:
java.io.IOException: Cannot run program "/data/soft/ffmpeg/ffmpeg", 拒绝访问
这是因为这个文件在Linux没有访问权限,应该在Linux系统中执行如下命令:
chmod 777 /data/soft/ffmpeg/ffmpeg
/data/soft/ffmpeg/ffmpeg为文件路径
四.自此,大功告成,如果大家还有什么问题的话,也可以在评论区留言