微信錄音接口的調用以及amr文件轉碼MP3文件的實現


最近實現錄音功能,主要涉及到錄音的上傳和下載,以及轉碼問題。微信,QQ默認的的音頻文件是amr格式的,而播放器卻不識別amr格式的音頻,必須盡行轉碼。amr文件分為兩種,一種是通用的amr格式,這種文件可以用任意播放器打開播放。但是還有另外一種amr文件,這種文件的后綴雖然是amr,但其實其內部並不是真正的amr格式。有不對的地方有請各方大神批評指正,具體實現如下:

1.調用微信錄音接口(開始錄音,暫停錄音,上傳錄音,)

具體接口請你參考 http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html

(1)record.jsp

$(function(){
    //調用微信開始錄音接口
    wx.ready(function(){
//開始錄音 alert("開始錄音"); wx.startRecord(); }); //結束錄音 wx.ready(function(){ wx.stopRecord({ success: function (res) { var localId = res.localId; alert("錄音結束"); saveAlert(localId); } }); }); //聲音標題,聲音描述 var voiceTitle = $("#voiceTitle").val(); var voiceDesc = $("#voiceDesc").val(); //將錄音上傳騰訊服務器 wx.ready(function(){ wx.uploadVoice({ localId: id, // 需要上傳的音頻的本地ID,由stopRecord接口獲得 isShowProgressTips: 1, // 默認為1,顯示進度提示 success: function (res) { var serverId = res.serverId; // 返回音頻的服務器端ID saveIntoLocation(serverId,voiceTitle,voiceDesc); } }); }); } function saveIntoLocation(id,title,desc){ var channelId = $("#channelIdResult").val(); var proId = $("#procastIdResult").val(); //alert(proId); var url = "/taiyang/fm/saveInfoJson.action"; var postData = { "en1.channelId" : channelId, "en1.proTitle" : title, "en1.proDesc" : desc, "en1.podcastId" : proId, "serverId" : id, "appid" : appId }; $.post(url, postData, function (data) { if(data.success){ openSuccessLayer(data.message); }else{ openFailureLayer(data.message); } },'json'); }
(2)WXFM.XML

 <package name="xiaovFmJson" extends="wxJsonData" namespace="/xiaov/fm">
!--微電台:保存錄音標題到本地數據庫-->
        <action name="saveInfoJson" class="com.jerehsoft.taiyang.fm.action.weixin.WxRadioStationAction"  method="saveInfo">
            <result type="json"></result>
        </action>
</package>

  

(3)WxRadioStationAction.java

public class WxRadioStationAction extends ActionSupport {
    Log log = LogFactory.getLog(this.getClass());
    private Map<String, Object> map1 = new HashMap<String, Object>();

    ActionContext ac = ActionContext.getContext();
    HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);

    private Long memberid;
    private String appid;
    private String openid;
    private String serverId;
    

    private boolean success;
    private String message;

    @EntityInject
    private WxFmProgramComment en;
    @EntityInject
    private WxFmProgrem en1;


    @Resource
    IWxFmProgremService programService;
    

     /**
     * 微電台錄音:保存錄音標題到本地數據庫
     *
     * @return
     * @throws Exception
     */
    public String saveInfo() throws Exception {
        //設置播客id
        try {
            //下載騰訊素材
            if (serverId != null && !serverId.equals("")) {
                CommAttachmentDetail file = mediaSer.downLoadFile(getAppid(), serverId);
                if (file != null) {
                    //picPath:amr文件存放的全路徑
                    String path = SystemConfig.get("sys.upload.dir");
                    String picPath = path + File.separator + file.getPathName() + file.getFileName();
                    //音頻轉換
                    Conversion conversion = new Conversion();

                    conversion.ToMp3("D:" + File.separator + "Program Files", picPath);

                    String fileName = file.getFileName().substring(0, file.getFileName().indexOf("."));

                    String picPathDataBase = file.getPathName() + fileName + ".mp3";

                    en1.setFileAddr(picPathDataBase);
                }
            }
            en1.setAppId(getAppid());
            //時間
            WxFmProgrem Progrem = programService.save(en1);
            success = true;
            map1.put("success", true);
            map1.put("message", "提交成功");
        } catch (Exception e) {
            message = "提交失敗";
            success = false;
            e.getStackTrace();
            e.printStackTrace();
        }

        return SUCCESS;
    }
 public String getAppid() {
        return appid;
    }

    public void setAppid(String appid) {
        this.appid = appid;
    }
 public String getServerId() {
        return serverId;
    }

    public void setServerId(String serverId) {
        this.serverId = serverId;
    }
}

  

(4) Conversion.java

public class Conversion {
    /**
     * 將上傳的錄音轉為mp3格式
     * @param webroot 項目的根目錄
     * @param sourcePath 文件的相對地址
     */
    public static void ToMp3(String webroot, String sourcePath){
        //File file = new File(sourcePath);
        String [] a =sourcePath.split("\\.");
        String targetPath = a[0]+".mp3";//轉換后文件的存儲地址,直接將原來的文件名后加mp3后綴名
        Runtime run = null;
        try {
            run = Runtime.getRuntime();
            long start=System.currentTimeMillis();
            //Process p=run.exec(webroot+"files/ffmpeg -i "+webroot+sourcePath+" -acodec libmp3lame "+webroot+targetPath);
            // 執行ffmpeg.exe,前面是ffmpeg.exe的地址,中間是需要轉換的文件地址,后面是轉換后的文件地址。-i是轉換方式,意思是可編碼解碼,mp3編碼方式采用的是libmp3lame
           Process p=run.exec(webroot+"/ffmpeg/bin/ffmpeg -i "+sourcePath+" -acodec libmp3lame "+targetPath);
            //釋放進程
            p.getOutputStream().close();
            p.getInputStream().close();
            p.getErrorStream().close();
            p.waitFor();
            long end=System.currentTimeMillis();
            //System.out.println(sourcePath+" convert success, costs:"+(end-start)+"ms");
            //刪除原來的文件
            /*if(file.exists()){
            file.delete();
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //run調用lame解碼器最后釋放內存
            run.freeMemory();
        }
    }

    public static void main(String[] args) {
        ToMp3("D:\\Program Files","E:\\a.amr");
    }
}

  (5)注意點:

3個地址:webroot,sourcePath為絕對路徑,webroot+"/ffmpeg/bin/ffmpeg"是自己電腦安裝的ffmpeg的安裝路徑

電腦要安裝FFMPEG,FFmpeg是一套可以用來記錄、轉換數字音頻、視頻,並能將其轉化為流的開源計算機程序。

FFMPEG的安裝請參考:http://www.bubuko.com/infodetail-786878.html

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM