当前位置: 移动技术网 > IT编程>开发语言>JavaScript > cocosCreator - GVoice(腾讯语音接入)

cocosCreator - GVoice(腾讯语音接入)

2020年07月08日  | 移动技术网IT编程  | 我要评论


环境:
win10
cocosCreator 2.1.4
xcode: 11.3.1(11c504)

GVoice官方地址:https://gcloud.qq.com/product/6
GVoice SDK 下载地址
在这里插入图片描述

Android 层

1.引入SDK

在这里插入图片描述

2.代码引入

在这里插入图片描述
GvoiceManager.java

	package org.cocos2dx.javascript.gvoice;

import android.app.Activity;
import android.content.Context;
import com.tencent.gcloud.voice.GCloudVoiceEngine;
import com.tencent.gcloud.voice.GCloudVoiceErrno;

public class GvoiceManager {
    private static GCloudVoiceEngine mVoiceEngine = null;
    private boolean bEngineInit = false;
    private volatile static GvoiceManager gvoiceManager = null;
    private static String appID = "腾讯语音申请的appid";
    private static String appKey = "腾讯语音申请的appKey";
    private static String openID = Long.toString(System.currentTimeMillis());
    private Context mContext;
    private Activity mActivity;

    private GvoiceManager() {
        bEngineInit = false;
    }

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

    public void setOpenID(String id) {
        openID = id;
        System.out.println("---引擎管理类设置openid:" + openID);
    }

    public int initGvoice(Activity activity) {
        int ret = 0;
        String logStr;
        if (!bEngineInit) {
            if (activity == null) {
                logStr = "Activity 不能为空!";
                System.out.println(logStr);
                return -1;
            }
            mActivity = activity;
            mContext = activity.getApplicationContext();

            mVoiceEngine = GCloudVoiceEngine.getInstance();
            if (mVoiceEngine == null) {
                logStr = "GCloudVoiceEngine 获取失败";
                System.out.println(logStr);
                ret = GCloudVoiceErrno.GCLOUD_VOICE_ENGINE_ERR;
                return ret;
            } else {
                logStr = "GCloudVoiceEngine 获取成功";
                System.out.println(logStr);
            }

            mVoiceEngine.init(mContext, mActivity);

            ret = mVoiceEngine.SetAppInfo(appID, appKey, openID);
            if (ret != 0) {
                logStr = "SetAppInfo 遇到错误,Error code: " + ret;
                System.out.println(logStr);
                return ret;
            } else {
                logStr = "SetAppInfo 成功";
                System.out.println(logStr);
            }

            ret = mVoiceEngine.Init();
            if (ret != 0) {
                logStr = "GCloudVoiceEngine 初始化遇到错误,Error code: " + ret;
                System.out.println(logStr);
                return ret;
            } else {
                logStr = "GCloudVoiceEngine 初始化成功";
                System.out.println(logStr);
            }

            bEngineInit = true;
        }
        return ret;
    }

    public GCloudVoiceEngine getVoiceEngine() {
        return mVoiceEngine;
    }

    public boolean isEngineInit() {
        return bEngineInit;
    }
}

GvoiceNotify.java
	package org.cocos2dx.javascript.gvoice;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.tencent.gcloud.voice.GCloudVoiceErrno;
import com.tencent.gcloud.voice.IGCloudVoiceNotify;

import org.cocos2dx.javascript.AppActivity;
import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;

public class GvoiceNotify implements IGCloudVoiceNotify {
    private Context mCtx;
    private static String mFileID;
    private static boolean uploadSuccess = false;
    private Handler mHandler;
    private volatile static GvoiceNotify gvoiceNotify = null;
    public static final int MSG_JOINROOM = 1000;
    public static final int MSG_QUITROOM = 1001;
    public static final int MSG_ROLECHANGED = 1002;
    public static final int MSG_UPLOADFILE = 1003;
    public static final int MSG_DOWNLOADFILE = 1004;
    public static final int MSG_PLAYRECODEFILE = 1005;
    public static final int MSG_APPLYKEY = 1006;
    public static final int MSG_STT = 1007;
    public static final int MSG_RSTT = 1008;
    public static final String KEY_STT = "stt";
    public static final String KEY_RSTT = "rstt";
    public static final String KEY_FILEID = "fileId";

    public GvoiceNotify() {
        super();
    }

    public GvoiceNotify(Context ctx) {
        super();
        mCtx = ctx;
    }

    public GvoiceNotify(Context ctx, Handler handler) {
        super();
        mCtx = ctx;
        mHandler = handler;
    }

    public static GvoiceNotify getInstance(Context ctx, Handler handler) {
        if (gvoiceNotify == null) {
            synchronized (GvoiceManager.class) {
                if (gvoiceNotify == null) {
                    gvoiceNotify = new GvoiceNotify(ctx, handler);
                }
            }
        }
        return gvoiceNotify;
    }

    @Override
    public void OnJoinRoom(int completeCode, String roomName, int memberID) {
        String msg;

        if (completeCode == GCloudVoiceErrno.GCloudVoiceCompleteCode.GV_ON_JOINROOM_SUCC) {
            msg = "OnJoinRoom 成功" + "Room name: " + roomName + "\t" + "Member ID: " + memberID + "\t";

            if (mHandler != null) {
                Message message = mHandler.obtainMessage();
                message.what = MSG_JOINROOM;
                message.arg1 = completeCode;
                mHandler.sendMessage(message);
            }
        } else {
            msg = "OnJoinRoom 遇到问题\t" + "Code: " + completeCode + "\t" + "Room name: " + roomName + "\t";
        }
        System.out.println(msg);
    }

    @Override
    public void OnStatusUpdate(int completeCode, String roomName, int memberID) {
        String msg = "OnStatusUpdate: \t" + "Code: " + completeCode + "\t" + "Room name: " + roomName + "\t"
                + "Member ID: " + memberID + "\t";
        System.out.println(msg);
    }

    @Override
    public void OnQuitRoom(int completeCode, String roomName) {
        String msg;

        if (completeCode == GCloudVoiceErrno.GCloudVoiceCompleteCode.GV_ON_QUITROOM_SUCC) {
            msg = "OnQuitRoom 成功\t" + "Code: " + completeCode + "\t" + "Room name: " + roomName + "\t";

            if (mHandler != null) {
                Message message = mHandler.obtainMessage();
                message.what = MSG_QUITROOM;
                message.arg1 = completeCode;
                mHandler.sendMessage(message);
            }
        } else {
            msg = "OnQuitRoom 遇到问题\t" + "Code: " + completeCode + "\t" + "Room name: " + roomName + "\t";
        }
        System.out.println(msg);
    }

    @Override
    public void OnMemberVoice(int[] members, int count) {
        String msg = "OnMemberVoice: \t" + "Count: " + count + "\t";
        for (int i = 0; i < members.length - 1; i += 2) {
            msg = msg + "Status of member " + i + " is: " + (i + 1) + "\t";
        }
        System.out.println(msg);
    }

    @Override
    public void OnMemberVoice(String roomName, int memberId, int status) {
        String msg = "OnMemberVoice in multi room: \t" + "Room name: " + roomName + "\t" + "MemberId: " + memberId + "\t" + "Status: " + status + "\t";
        System.out.println(msg);
    }

    static private AppActivity getCtx() {
        return (AppActivity) AppActivity.getContext();
    }

    @Override
    public void OnUploadFile(int completeCode, String filePath, String fileID) {
        String msg;
        if (completeCode == GCloudVoiceErrno.GCloudVoiceCompleteCode.GV_ON_UPLOAD_RECORD_DONE) {
            uploadSuccess = true;
            mFileID = fileID;
            msg = "UploadFile 成功\t" + "File path: " + filePath + "\t" + "File ID: " + fileID + "\t";

            if (mHandler != null) {
                Message message = mHandler.obtainMessage();
                message.what = MSG_UPLOADFILE;
                message.arg1 = completeCode;
                Bundle fileidResult = new Bundle();
                fileidResult.putString(KEY_FILEID, fileID);
                message.setData(fileidResult);
                String ID = "\"" + fileID + "\"";
                int time = RecordActivity.Time;
                final String str = String.format("cc.globalMgr.voiceFrame.UpLoafVoiceId(" + ID + "," + time + ")");
                getCtx().runOnGLThread(new Runnable() {
                    @Override
                    public void run() {
                        Cocos2dxJavascriptJavaBridge.evalString(str);
                    }
                });
            }
        } else {
            msg = "UploadFile 遇到错误\t" + "Code: " + completeCode + "\t" + "File path: " + filePath + "\t" + "File ID: "
                    + fileID + "\t";
        }
        System.out.println(msg);
    }

    @Override
    public void OnDownloadFile(int completeCode, String filePath, String fileID) {

        String msg;
        if (completeCode == GCloudVoiceErrno.GCloudVoiceCompleteCode.GV_ON_DOWNLOAD_RECORD_DONE) {
            msg = "DownloadFile 成功\t" + "File path: " + filePath + "\t" + "File ID: " + fileID + "\t";

            if (mHandler != null) {
                Message message = mHandler.obtainMessage();
                message.what = MSG_DOWNLOADFILE;
                message.arg1 = completeCode;
                mHandler.sendMessage(message);
                // startPlay
                PlayActivity.startPlay();
                final String str = String.format("cc.globalMgr.voiceFrame.downloadPlayVoice(\"" + fileID + "\")");
                getCtx().runOnGLThread(new Runnable() {
                    @Override
                    public void run() {
                        Cocos2dxJavascriptJavaBridge.evalString(str);
                    }
                });
            }
        } else {
            msg = "DownloadFile 失败\t" + "Code: " + completeCode + "\t" + "File path: " + filePath + "\t" + "File ID: "
                    + fileID + "\t";
        }
        System.out.println(msg);
    }

    @Override
    public void OnPlayRecordedFile(int completeCode, String filePath) {
        String msg = "OnPlayRecordedFile: \t" + "Code: " + completeCode + "\t" + "File path: " + filePath + "\t";
        System.out.println(msg);

        if (completeCode == GCloudVoiceErrno.GCloudVoiceCompleteCode.GV_ON_PLAYFILE_DONE) {
            if (mHandler != null) {
                Message message = mHandler.obtainMessage();
                message.what = MSG_PLAYRECODEFILE;
                message.arg1 = completeCode;
                mHandler.sendMessage(message);

            }
        }
    }

    @Override
    public void OnApplyMessageKey(int completeCode) {
        String msg;

        if (completeCode == GCloudVoiceErrno.GCloudVoiceCompleteCode.GV_ON_MESSAGE_KEY_APPLIED_SUCC) {
            if (mHandler != null) {
                Message message = mHandler.obtainMessage();
                message.what = MSG_APPLYKEY;
                message.arg1 = completeCode;
                mHandler.sendMessage(message);
            }
            msg = "OnApplyMessageKey 成功";
        } else {
            msg = "OnApplyMessageKey 遇到错误\t" + "Code: " + completeCode + "\t";
        }
        System.out.println(msg);
    }

    @Override
    public void OnSpeechToText(int completeCode, String fileID, String result) {
        String msg;

        if (completeCode == GCloudVoiceErrno.GCloudVoiceCompleteCode.GV_ON_STT_SUCC) {
            msg = "OnSpeechToText 成功\t" + "Result: " + result + "\t";
            if (mHandler != null) {
                Message message = mHandler.obtainMessage();
                message.what = MSG_STT;
                message.arg1 = completeCode;
                Bundle sttResult = new Bundle();
                sttResult.putString(KEY_STT, result);
                message.setData(sttResult);
                mHandler.sendMessage(message);
            }
        } else {
            msg = "OnSpeechToText 遇到错误\t" + "Code: " + completeCode + "\t" + "FileID: " + fileID + "\n";
        }
        System.out.println(msg);
    }

    @Override
    public void OnRecording(char[] pAudioData, int nDataLength) {
        String msg = "OnRecording\t";
        System.out.println(msg);
    }

    @Override
    public void OnStreamSpeechToText(int completeCode, int errCode, String result, String voicePath) {
        String msg;

        if (completeCode == GCloudVoiceErrno.GCloudVoiceCompleteCode.GV_ON_RSTT_SUCC) {
            msg = "OnStreamSpeechToText 成功\t" + "Result: " + result + "\t";

            if (mHandler != null) {
                Message message = mHandler.obtainMessage();
                message.what = MSG_RSTT;
                message.arg1 = completeCode;
                Bundle rsttResult = new Bundle();
                rsttResult.putString(KEY_RSTT, result);
                message.setData(rsttResult);
                mHandler.sendMessage(message);
            }
        } else {
            msg = "OnStreamSpeechToText 遇到错误\t" + "Code: " + completeCode + "\t" + "ErrCode: " + errCode + "\t"
                    + "VoicePath: " + voicePath + "\t";
        }
        System.out.println(msg);
    }

    @Override
    public void OnRoleChanged(int completeCode, String roomName, int memberId, int role) {
        String msg = "OnRoleChanged: \t" + "Code: " + completeCode + "\t" + "RoomName: " + roomName + "\t"
                + "MemberId: " + memberId + "\t" + "Role: " + role + "\t";
        System.out.println(msg);

        if (completeCode == GCloudVoiceErrno.GCloudVoiceCompleteCode.GV_ON_ROLE_SUCC) {
            if (mHandler != null) {
                Message message = mHandler.obtainMessage();
                message.what = MSG_ROLECHANGED;
                message.arg1 = completeCode;
                message.arg2 = role;
                mHandler.sendMessage(message);
            }
        }
    }

    @Override
    public void OnEvent(int eventId, String eventInfo) {
        String msg = "OnEvent: \t" + "EventId: " + eventId + "\t" + "EventInfo: " + eventInfo + "\t";
        System.out.println(msg);
    }

    public String getFileID() {
        if (uploadSuccess) {
            return mFileID;
        } else {
            return "";
        }
    }
}

MsgActivity.java
	package org.cocos2dx.javascript.gvoice;

import android.content.Context;
import android.os.Handler;

import com.tencent.gcloud.voice.GCloudVoiceEngine;
import com.tencent.gcloud.voice.GCloudVoiceErrno;

import org.cocos2dx.javascript.AppActivity;

public class MsgActivity {
    private static Context mCtx;
    private static GCloudVoiceEngine mEngine;
    private GvoiceManager mGvoiceManager;
    private GvoiceNotify mNotify;
    private static Handler mHandler;
    private static boolean isAppliedKey;
    private static String msgStr;
    private static PlayActivity mPlayActivity;
    private static RecordActivity mRecordActivity;

    private volatile static MsgActivity MsgActivity = null;

    public MsgActivity() {

    }

    public MsgActivity(Context ctx) {
        mCtx = ctx;
    }

    public MsgActivity(Context ctx, Handler handler) {
        mCtx = ctx;
        mHandler = handler;
    }

    public static MsgActivity getInstance(Context ctx, Handler handler) {
        if (MsgActivity == null) {
            synchronized (GvoiceManager.class) {
                if (MsgActivity == null) {
                    MsgActivity = new MsgActivity(ctx, handler);
                }
            }
        }
        return MsgActivity;
    }

    public void setNotify() {
        mGvoiceManager = GvoiceManager.getInstance();
        mEngine = mGvoiceManager.getVoiceEngine();
        mNotify = new GvoiceNotify(mCtx, mHandler);
        mEngine.SetNotify(mNotify);
    }

    public void setKeyForMsg(boolean isKey) {
        isAppliedKey = isKey;
        System.out.println("----是否获取key:" + isAppliedKey);
    }

    private static void applyMsgKey() {
        int msTimeout = 10000;
        int ret = mEngine.ApplyMessageKey(msTimeout);
        if (ret == GCloudVoiceErrno.GCLOUD_VOICE_SUCC) {
            msgStr = "ApplyMessageKey,结果将通过回调方法OnApplyMessageKey通知";
        } else {
            msgStr = "ApplyMessageKey遇到错误 \tError code: " + ret;
        }
        System.out.println(msgStr);
    }

    private static void record() {
        if (isAppliedKey) {
            msgStr = "进入录音功能页面";
            mRecordActivity = RecordActivity.getInstance(mCtx, mHandler);
            mRecordActivity.setNotify();
            mRecordActivity.getFileAndPathForRecord();
        } else {
            msgStr = "未申请消息许可";
        }
        System.out.println(msgStr);
    }

    static private AppActivity getCtx() {
        return (AppActivity) AppActivity.getContext();
    }

    public static void play(String ID, int wxid) {
        if (isAppliedKey) {
            msgStr = "进入播放功能页面";
            System.out.println(msgStr);
            mPlayActivity = PlayActivity.getInstance(mCtx, mHandler);
            mPlayActivity.setNotify();
            mPlayActivity.getFileAndPathForDownload(ID);
        } else {
            msgStr = "未申请消息许可";
            System.out.println(msgStr);
        }
    }
}

PlayActivity.java
	package org.cocos2dx.javascript.gvoice;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.widget.ImageButton;
import com.tencent.gcloud.voice.GCloudVoiceEngine;
import com.tencent.gcloud.voice.GCloudVoiceErrno;
import java.io.File;


public class PlayActivity {
    private Context mCtx;
    private GvoiceManager mGvoiceManager;
    private static GCloudVoiceEngine mEngine;
    private static GvoiceNotify mNotify;
    private Handler mHandler;
    private static String msgStr;
    private static String mDownloadPath;         
    private static String mFileID;            
    private static boolean isDownload;
    private static int msTimeout = 10000;


    private volatile static PlayActivity PlayActivity = null;
    public PlayActivity() {

    }

    public PlayActivity(Context ctx) {
        mCtx = ctx;
    }

    public PlayActivity(Context ctx, Handler handler) {
        mCtx = ctx;
        mHandler = handler;
    }

    public static PlayActivity getInstance(Context ctx, Handler handler) {
        if (PlayActivity == null) {
            synchronized (GvoiceManager.class) {
                if (PlayActivity == null) {
                    PlayActivity = new PlayActivity(ctx, handler);
                }
            }
        }
        return PlayActivity;
    }

    protected void setNotify() {
        mGvoiceManager = GvoiceManager.getInstance();
        mEngine = mGvoiceManager.getVoiceEngine();
        mNotify = new GvoiceNotify(mCtx, mHandler);
        mEngine.SetNotify(mNotify);
    }

    public void setIsDownLoadForMsg(boolean isDown){
        isDownload = isDown;
    }

    protected void getFileAndPathForDownload(String mFileID){
        File downloadFile = new File(mCtx.getFilesDir(), "download.dat");
        mDownloadPath = downloadFile.getAbsolutePath();
        PlayActivity.downloadPlayfile(mFileID);
    }

    private static void downloadPlayfile(String mFileID) {
//        File downloadFile = new File(mCtx.getFilesDir(), "download.dat");
//        mDownloadPath = downloadFile.getAbsolutePath();
        //mFileID = mNotify.getFileID();
        if (mFileID == null || mFileID.length() == 0) {
            msgStr = "FileID 为空,请先设置FileID,或先通过\"录音功能页面\"录制一段音频";
        }
        else {
            int ret = mEngine.DownloadRecordedFile(mFileID, mDownloadPath, msTimeout);
            if (ret == GCloudVoiceErrno.GCLOUD_VOICE_SUCC) {
                msgStr = "正在下载录音文件...";
            }
            else {
                msgStr = "下载录音文件遇到错误 \tError code: " + ret;
            }
        }
        System.out.println(msgStr);
    }

    public static void startPlay() {
        //if (isDownload) {
            int ret = mEngine.PlayRecordedFile(mDownloadPath);
            if (ret == GCloudVoiceErrno.GCLOUD_VOICE_SUCC) {
                msgStr = "开始播放录音文件...";
            }
            else {
                msgStr = "播放录音文件遇到错误 \tError code: " + ret;
            }
       // }
        //else {
            msgStr = "请先下载录音文件!";
        //}
        System.out.println(msgStr);
    }

    public static void stopPlay() {
        int ret = mEngine.StopPlayFile();
        if (ret == GCloudVoiceErrno.GCLOUD_VOICE_SUCC) {
            msgStr = "播放停止";
        } else {
            msgStr = "未能成功停止播放 \tError code: " + ret;
        }
        System.out.println(msgStr);
    }
}

RealtimeActivity.java
	
package org.cocos2dx.javascript.gvoice;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.widget.ImageButton;
import com.tencent.gcloud.voice.GCloudVoiceEngine;
import com.tencent.gcloud.voice.GCloudVoiceErrno;
import static org.cocos2dx.javascript.gvoice.GvoiceNotify.MSG_JOINROOM;
import static org.cocos2dx.javascript.gvoice.GvoiceNotify.MSG_QUITROOM;


public class RealtimeActivity {
    private static Context mCtx;
    private GvoiceManager mGvoiceManager;
    private static GCloudVoiceEngine mEngine;
    private static Handler mHandler;
    private GvoiceNotify mNotify;
    private static String msgStr;
    private static String mRoomName;       
    public static final String TAG_ROOMNAME = "com.tencent.gvoice.roomname";
    private static int msTimeOut = 10000;          
    private int mRole = 2;                    
    private static Intent mIntent;

    private volatile static RealtimeActivity RealtimeActivity = null;
    public RealtimeActivity() {

    }

    public RealtimeActivity(Context ctx) {
        mCtx = ctx;
    }

    public RealtimeActivity(Context ctx, Handler handler) {
        mCtx = ctx;
        mHandler = handler;
    }

    public static RealtimeActivity getInstance(Context ctx, Handler handler) {
        if (RealtimeActivity == null) {
            synchronized (GvoiceManager.class) {
                if (RealtimeActivity == null) {
                    RealtimeActivity = new RealtimeActivity(ctx, handler);
                }
            }
        }
        return RealtimeActivity;
    }

    public void setNotify() {
        mGvoiceManager = GvoiceManager.getInstance();
        mEngine = mGvoiceManager.getVoiceEngine();
        mNotify = new GvoiceNotify(mCtx, mHandler);
        mEngine.SetNotify(mNotify);
    }

    protected void setRoomNumber(String roomNum){
        mRoomName = roomNum;
    }

    public RealtimeActivity getRealtimeActivity() {
        return RealtimeActivity;
    }
}

RecordActivity.java
	package org.cocos2dx.javascript.gvoice;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.widget.ImageButton;
import com.tencent.gcloud.voice.GCloudVoiceEngine;
import com.tencent.gcloud.voice.GCloudVoiceErrno;
import java.io.File;

public class RecordActivity {
    private ImageButton returnIbtn;
    private ImageButton startRecordIbtn;
    private ImageButton stopRecordIbtn;
    private ImageButton uploadIbtn;

    private Context mCtx;
    private GvoiceManager mGvoiceManager;
    private static GCloudVoiceEngine mEngine;
    private GvoiceNotify mNotify;
    private Handler mHandler;
    private static String msgStr;
    private static String mRecordingPath;     
    private String mFileID;          
    private boolean isUpload;
    private int msTimeout = 10000;
    public static int Time = 2;

    private volatile static RecordActivity RecordActivity = null;
    public RecordActivity() {

    }

    public RecordActivity(Context ctx) {
        mCtx = ctx;
    }

    public RecordActivity(Context ctx, Handler handler) {
        mCtx = ctx;
        mHandler = handler;
    }

    public static RecordActivity getInstance(Context ctx, Handler handler) {
        if (RecordActivity == null) {
            synchronized (GvoiceManager.class) {
                if (RecordActivity == null) {
                    RecordActivity = new RecordActivity(ctx, handler);
                }
            }
        }
        return RecordActivity;
    }

    protected void setNotify() {
        mGvoiceManager = GvoiceManager.getInstance();
        mEngine = mGvoiceManager.getVoiceEngine();
        mNotify = new GvoiceNotify(mCtx, mHandler);
        mEngine.SetNotify(mNotify);
    }

    protected void getFileAndPathForRecord(){
        File recordingFile = new File(mCtx.getFilesDir(), "recording.dat");
        mRecordingPath = recordingFile.getAbsolutePath();
    }

    private static void startRecord() {
        int ret = mEngine.StartRecording(mRecordingPath);
        if (ret == GCloudVoiceErrno.GCLOUD_VOICE_SUCC) {
            msgStr = "录音开始...";
        } else {
            msgStr = "未能成功开始录音 \tError code: " + ret;
        }
        System.out.println(msgStr);
    }

    //自动播放,传参数时间time

   private static void stopRecord(int time) {
       Time = time;
       int ret = mEngine.StopRecording();
       if (ret == GCloudVoiceErrno.GCLOUD_VOICE_SUCC) {
           msgStr = "录音停止";
           RecordActivity.uploadRecordfile();
       } else {
           msgStr = "未能成功停止录音 \tError code: " + ret;
       }
       System.out.println(msgStr);
   }

    //     private static void stopRecord() {
    //     //Time = time;
    //     int ret = mEngine.StopRecording();
    //     if (ret == GCloudVoiceErrno.GCLOUD_VOICE_SUCC) {
    //         msgStr = "录音停止";
    //         RecordActivity.uploadRecordfile();
    //     } else {
    //         msgStr = "未能成功停止录音 \tError code: " + ret;
    //     }
    //     System.out.println(msgStr);
    // }

    private void uploadRecordfile() {
        int ret = mEngine.UploadRecordedFile(mRecordingPath, msTimeout);
        if (ret == GCloudVoiceErrno.GCLOUD_VOICE_SUCC) {
            msgStr = "正在上传录音文件,上传结果通过回调方法OnUploadFile通知";
        } else {
            msgStr = "录音文件未能成功上传 \tError code: " + ret;
        }
        System.out.println(msgStr);
    }
}

SDKWrapper.java
	package org.cocos2dx.javascript.gvoice;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.opengl.GLSurfaceView;
import android.os.Bundle;

public class SDKWrapper {
	private final static boolean PACKAGE_AS = true;
	private static Class<?> mClass = null;

	private static SDKWrapper mInstace = null;
	public static SDKWrapper getInstance() {
		if (null == mInstace){
			mInstace = new SDKWrapper();
			if (PACKAGE_AS) {
				try {
					String fullName = "com.anysdk.framework.PluginWrapper";
					mClass = Class.forName(fullName);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return mInstace;	
	}
	
	public void init(Context context) {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("init", Context.class).invoke(mClass, context);
			} catch (Exception e) {
				e.printStackTrace();
			}
			SDKWrapper.nativeLoadAllPlugins();
		}
		
	}
	
	public void setGLSurfaceView(GLSurfaceView view) {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("setGLSurfaceView", GLSurfaceView.class).invoke(mClass, view);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void onResume() {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("onResume").invoke(mClass);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onPause() {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("onPause").invoke(mClass);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onDestroy() {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("onDestroy").invoke(mClass);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("onActivityResult", int.class, int.class, Intent.class).invoke(mClass, requestCode, resultCode, data);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onNewIntent(Intent intent) {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("onNewIntent", Intent.class).invoke(mClass, intent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onRestart() {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("onRestart").invoke(mClass);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}	
	}

	public void onStop() {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("onStop").invoke(mClass);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onBackPressed() {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("onBackPressed").invoke(mClass);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onConfigurationChanged(Configuration newConfig) {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("onConfigurationChanged", Configuration.class).invoke(mClass, newConfig);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onRestoreInstanceState(Bundle savedInstanceState) {
			if (PACKAGE_AS) {
			try {
				mClass.getMethod("onRestoreInstanceState", Bundle.class).invoke(mClass, savedInstanceState);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onSaveInstanceState(Bundle outState) {
			if (PACKAGE_AS) {
			try {
				mClass.getMethod("onSaveInstanceState", Bundle.class).invoke(mClass, outState);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onStart() {
		if (PACKAGE_AS) {
			try {
				mClass.getMethod("onStart").invoke(mClass);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private static native void nativeLoadAllPlugins();
}

Utils.java
	package org.cocos2dx.javascript.gvoice;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import java.util.Timer;
import java.util.TimerTask;

public class Utils {
    private static String TAG_DIALOG = "GVoiceDialog";
    private static String TAG_LOG = "gvoice";
    private static final int MSG_POLL = 1;

    static class PollHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            GvoiceManager manager = GvoiceManager.getInstance();
            switch (msg.what) {
                case MSG_POLL:
                    if (manager != null && manager.isEngineInit()) {
                        manager.getVoiceEngine().Poll();
                        System.out.println("Poll");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    public static void poll() {
        final PollHandler mHandler = new PollHandler();
        TimerTask pollTask = new TimerTask() {
            @Override
            public void run() {
                Message msg = mHandler.obtainMessage();
                msg.what = MSG_POLL;
                mHandler.sendMessage(msg);
            }
        };

        Timer timer = new Timer(true);
        timer.schedule(pollTask, 500, 500);
    }

    public static void startTargetActivity(Context ctx, Class<? extends Activity> activityClass) {
        Intent intent = new Intent(ctx, activityClass);
        ctx.startActivity(intent);
    }
}

3.AppActivity.java 中初始化

/****************************************************************************
 Copyright (c) 2015-2016 Chukong Technologies Inc.
 Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.

 http://www.cocos2d-x.org

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/
package org.cocos2dx.javascript;

import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;

import com.tencent.gcloud.voice.GCloudVoiceEngine;
import com.tencent.gcloud.voice.GCloudVoiceErrno;
import org.cocos2dx.javascript.gvoice.GvoiceManager;
import org.cocos2dx.javascript.gvoice.GvoiceNotify;
import org.cocos2dx.javascript.gvoice.MsgActivity;
import org.cocos2dx.javascript.gvoice.PlayActivity;
import org.cocos2dx.javascript.gvoice.RealtimeActivity;
import org.cocos2dx.javascript.gvoice.Utils;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import static org.cocos2dx.javascript.gvoice.GvoiceNotify.MSG_JOINROOM;
import static org.cocos2dx.javascript.gvoice.GvoiceNotify.MSG_QUITROOM;

//引入语音头文件

public class AppActivity extends Cocos2dxActivity {
    private static GvoiceManager mManager;
    private static String msgStr;
    private static GCloudVoiceEngine engine;
    private static MsgActivity curMsg;
    private String mFileID;
    private static Handler sHandler;
    private static Context mCtx;
    private static RealtimeActivity curReal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mCtx = this;
        System.loadLibrary("GCloudVoice");
        mManager = GvoiceManager.getInstance();
        if (mManager != null) {
            int ret = mManager.initGvoice(this);
            if (ret == 0) {
                msgStr = "GVoice 初始化成功";
            } else {
                msgStr = "GVoice 初始化遇到错误\t Error code:" + ret;
            }
            System.out.println(msgStr);
            engine = mManager.getVoiceEngine();
        }
        sHandler = new RealtimeHandler();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        SDKWrapper.getInstance().onResume();
        if (mManager.isEngineInit()) {
            engine.Resume();
        }
        Utils.poll();
    }

    @Override
    protected void onPause() {
        super.onPause();
        SDKWrapper.getInstance().onPause();
        if (mManager.isEngineInit()) {
            engine.Pause();
        }
    }

    //////////////////////////////////////

    private static void enterMsgMode() {
        if (mManager.isEngineInit()) {
            int ret = engine.SetMode(GCloudVoiceEngine.Mode.Messages);
            if (ret == GCloudVoiceErrno.GCLOUD_VOICE_SUCC) {
                msgStr = "GVoice已成功设置为离线消息模式!";
                curMsg = MsgActivity.getInstance(mCtx, sHandler);
                curMsg.setNotify();
                System.out.println("启用离线语音类");
            } else {
                msgStr = "设置GVoice为离线消息模式遇到错误!\n Error code: " + ret;
            }
            System.out.println(msgStr);
        } else {
            msgStr = "GVoice还没有成功初始化,请先初始化!";
            System.out.println(msgStr);
        }
    }

    public class RealtimeHandler extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_JOINROOM:
                    System.out.println("----进入小队成功");

                    break;
                case MSG_QUITROOM:
                    finish();
                    System.out.println("----退出房间");
                    break;
                case GvoiceNotify.MSG_APPLYKEY:
                    if (msg.arg1 == GCloudVoiceErrno.GCloudVoiceCompleteCode.GV_ON_MESSAGE_KEY_APPLIED_SUCC) {
                        curMsg.setKeyForMsg(true);
                        System.out.println("----应用key成功");
                    }
                    break;
                case GvoiceNotify.MSG_UPLOADFILE:
                    if (msg.arg1 == GCloudVoiceErrno.GCloudVoiceCompleteCode.GV_ON_UPLOAD_RECORD_DONE) {
                        mFileID = msg.getData().getString(GvoiceNotify.KEY_FILEID);
                        msgStr = "录音文件上传成功 \t FileID: " + mFileID;
                    } else {
                        msgStr = "录音文件上传失败 \t Error code: " + msg.arg1;
                    }
                    System.out.println(msgStr);
                    break;
                case GvoiceNotify.MSG_DOWNLOADFILE:
                    PlayActivity curPlay = PlayActivity.getInstance(mCtx, sHandler);
                    curPlay.setIsDownLoadForMsg(true);
                    System.out.println("----设置下载文件");
                    break;
                case GvoiceNotify.MSG_PLAYRECODEFILE:
                    msgStr = "录音播放完成";
                    System.out.println(msgStr);
                    break;
                default:
                    break;
            }
        }
    }
}

iOS层

引入SDK(③) 引入脚本(①、②)

在这里插入图片描述
MessageViewController.h

/*******************************************************************************\
** GVoiceDemo:MessageViewController.h
** Created by CZ(cz.devnet@gmail.com) on 24/05/2017
**
**  Copyright © 2017 gvoice. All rights reserved.
\*******************************************************************************/


#import <UIKit/UIKit.h>
//#import "GVoice.h"

@interface MessageViewController : UIViewController {
    
}
@end

MessageViewController.mm

/*******************************************************************************\
** GVoiceDemo:MessageViewController.m
** Created by CZ(cz.devnet@gmail.com) on 24/05/2017
**
**  Copyright © 2017 gvoice. All rights reserved.
\*******************************************************************************/


#import "MessageViewController.h"
#import "GVoice/include/GVoice.h"
#import "cocos2d.h"
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
static NSString *filePath;
static NSString *downFilePath;
static int t = 0;
@interface MessageViewController ()<GVGCloudVoiceDelegate>
@property (weak, nonatomic) IBOutlet UIButton *applyAuthKeyBtn;
@property (weak, nonatomic) IBOutlet UIButton *startRecordBtn;
@property (weak, nonatomic) IBOutlet UIButton *uploadBtn;
@property (weak, nonatomic) IBOutlet UIButton *downloadBtn;
@property (weak, nonatomic) IBOutlet UIButton *startPlayBtn;

@property (strong, nonatomic) NSTimer *pollTimer;
//@property (strong, nonatomic) NSString *file;
//@property (strong, nonatomic) NSString *downFilePath;
@property (strong, nonatomic) NSString *fileID;
@end


@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //self.view.backgroundColor = [UIColor grayColor];
    [GVGCloudVoice sharedInstance].delegate = self;
    [[GVGCloudVoice sharedInstance] setAppInfo:"申请的" withKey:"申请的" andOpenID:"abc"];
    [[GVGCloudVoice sharedInstance] initEngine];
    _pollTimer = [NSTimer scheduledTimerWithTimeInterval:1.000/15 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [[GVGCloudVoice sharedInstance] poll];
    }];
   
}

//- (void)didReceiveMemoryWarning {
//    [super didReceiveMemoryWarning];
//    // Dispose of any resources that can be recreated.
//
//}

- (void) warnning: (NSString *) msg {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"WARNING" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
    }]];
    [self presentViewController:alert animated:YES completion:^{
        //
    }];
}
+ (void)onApplyAuthKey {
    [[GVGCloudVoice sharedInstance] setAppInfo:"申请的" withKey:"申请的" andOpenID:"your_open_id"];
    [[GVGCloudVoice sharedInstance] setMode:Messages];
    [[GVGCloudVoice sharedInstance] applyMessageKey:18000];
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //_file = docPath
    filePath = [NSString stringWithFormat:@"%@/%s", docPath, "voice.dat"];
    downFilePath = [NSString stringWithFormat:@"%@/%s", docPath, "voice_downlad.dat"];
    std::string FilePath = [filePath UTF8String];
    std::string downfilepath = [downFilePath UTF8String];
    NSString* script = [NSString stringWithFormat:@"cc.globalMgr.voiceFrame.setFilePath(\"%s\",\"%s\");", FilePath.c_str(),downfilepath.c_str()];
    //NSString* script = [NSString stringWithFormat:@"require('HelloWorld').getInstance().setFilePath(\"%s\");", FilePath.c_str()];
    const char*  b = [script UTF8String];
    NSLog(@"GVoice 申请KEY%s",b);
    se::ScriptEngine::getInstance()->evalString(b);
}
//- (IBAction)startRecord:(id)sender {
//    static BOOL once = YES;
//    if (once) {
//        [_startRecordBtn setTitle:@"StopRecord" forState:UIControlStateNormal];
//        once = NO;
//        [[GVGCloudVoice sharedInstance] startRecording:[_filePath cStringUsingEncoding:NSUTF8StringEncoding]];
//    } else {
//        [_startRecordBtn setTitle:@"StartRecord" forState:UIControlStateNormal];
//        once = YES;
//        [[GVGCloudVoice sharedInstance] stopRecording];
//    }
//}

+(void)startReCord:(NSString*)file{
    //printf(filePath)
    NSLog(@"文件逻辑%@",file);
//    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    filePath = [NSString stringWithFormat:@"%@/%s", docPath, "voice.dat"];
    
    [[GVGCloudVoice sharedInstance] startRecording:[file cStringUsingEncoding:NSUTF8StringEncoding]];
}

+(void)stopReCord:(NSString*)file andContent: (int)time{
    t = time;
    [[GVGCloudVoice sharedInstance] stopRecording];
     [MessageViewController onUpload:file];
}

+ (void)onUpload:(NSString*)file{
    [[GVGCloudVoice sharedInstance] uploadRecordedFile:[file cStringUsingEncoding:NSUTF8StringEncoding] timeout:18000];
}

+ (void)onDownload:(NSString*)fileID andContent:(NSString*)downloadfile {
    NSLog(@"开始下载%@",downloadfile);
    NSLog(@"开始下载%@",fileID);
    [[GVGCloudVoice sharedInstance] downloadRecordedFile:[fileID cStringUsingEncoding:NSUTF8StringEncoding] filePath:[downloadfile cStringUsingEncoding:NSUTF8StringEncoding] timeout:18000];
}

//- (IBAction)onStartPlay:(id)sender {
//    static BOOL once = YES;
//    if (once) {
//        [_startPlayBtn setTitle:@"StopPlay" forState:UIControlStateNormal];
//        once = NO;
//        [[GVGCloudVoice sharedInstance] playRecordedFile:[downFilePath cStringUsingEncoding:NSUTF8StringEncoding]];
//    } else {
//        [_startPlayBtn setTitle:@"StartPlay" forState:UIControlStateNormal];
//        once = YES;
//        [[GVGCloudVoice sharedInstance] stopPlayFile];
//    }
//}

-(void)StartPlay:(NSString*)downloadfile{
    NSLog(@"播放语音%@",downloadfile);
    [[GVGCloudVoice sharedInstance] playRecordedFile:[downloadfile cStringUsingEncoding:NSUTF8StringEncoding]];
}

+(void)StopPlay{
    [[GVGCloudVoice sharedInstance] stopPlayFile];
}

#pragma mark delegate

- (void) onJoinRoom:(enum GCloudVoiceCompleteCode) code withRoomName: (const char * _Nullable)roomName andMemberID:(int) memberID {
    
}

- (void) onStatusUpdate:(enum GCloudVoiceCompleteCode) status withRoomName: (const char * _Nullable)roomName andMemberID:(int) memberID {
    
}
///var/mobile/Containers/Data/Application/21D4281A-6B2B-43F7-A62E-04EA8F826C78/Documents/voice_downlad.dat
///var/mobile/Containers/Data/Application/21D4281A-6B2B-43F7-A62E-04EA8F826C78/Documents/voice_downlad.dat
- (void) onQuitRoom:(enum GCloudVoiceCompleteCode) code withRoomName: (const char * _Nullable)roomName {
    
}

- (void) onMemberVoice:    (const unsigned int * _Nullable)members withCount: (int) count {
}

- (void) onUploadFile: (enum GCloudVoiceCompleteCode) code withFilePath: (const char * _Nullable)filePath andFileID:(const char * _Nullable)fileID  {
    _fileID = [NSString stringWithFormat:@"%s", fileID];
    //[self onDownload:_fileID];
    //[self warnning:@"Upload Success"];
    std::string FilePath = [_fileID UTF8String];
    //std::string downfilepath = [downFilePath UTF8String];
    NSString* script = [NSString stringWithFormat:@"cc.globalMgr.voiceFrame.UpLoafVoiceId(\"%s\",%d);", FilePath.c_str(),t];
    const char*  b = [script UTF8String];
    NSLog(@"%s",b);
    NSLog(@"上传完成%@",_fileID);
    se::ScriptEngine::getInstance()->evalString(b);
}

- (void) onDownloadFile: (enum GCloudVoiceCompleteCode) code  withFilePath: (const char * _Nullable)filePath andFileID:(const char * _Nullable)fileID {
    NSString *msg;
    msg = @"Download File Success";
    
    //[self warnning:msg];
    //[self StartPlay];
    NSString* downloadfilepath = [NSString stringWithFormat:@"%s", filePath];
    NSLog(@"下载完成%@",downloadfilepath);
   
    NSString* script = [NSString stringWithFormat:@"cc.globalMgr.voiceFrame.downloadPlayVoice(\"%s\");", fileID];
    const char*  b = [script UTF8String];
    se::ScriptEngine::getInstance()->evalString(b);
    
    [self StartPlay:downloadfilepath];
}

- (void) onPlayRecordedFile:(enum GCloudVoiceCompleteCode) code withFilePath: (const char * _Nullable)filePath {
    
//    NSString *msg;
//    msg = @"Finish Play File";
//    [self warnning:msg];
}

- (void) onApplyMessageKey:(enum GCloudVoiceCompleteCode) code {
//    NSString *msg;
//    msg = @"Apply AuthKey Success";
    //[self warnning:msg];
}

- (void) onSpeechToText:(enum GCloudVoiceCompleteCode) code withFileID:(const char * _Nullable)fileID andResult:( const char * _Nullable)result {
}

- (void) onRecording:(const unsigned char* _Nullable) pAudioData withLength: (unsigned int) nDataLength {
    
}

- (void) onStreamSpeechToText:(enum GCloudVoiceCompleteCode) code withError:(int) error andResult:(const char *_Nullable)result {
    
}



/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
@end

添加库

`libc++.tbd`、
`libsqlite3.0.tbd`、
`libz.dylib`、
`libz.1.2.5.tbd`、
`libresolv.9.tbd`、
`SystemConfiguration.framework`、
`CoreTelephony.framework`、
`AVFoundation.framework`、
`AudioToolBox.framework`、
`CFNetwork.framework`。

//腾讯语音新增的3个库
`CoreAudio.framework`
`libstdc++.6.0.9.tbd`
`security.framework`

AppController中调用

导入MessageViewController.h和MessageViewController.mm两个文件
在AppController.mm文件中加入MessageViewController.h头文件,并在_viewController.wantsFullScreenLayout = YES;下边加入这两行文件
MessageViewController* Voiceview = [[MessageViewController alloc] init];
[_viewController.view addSubview:Voiceview.view];
Build Settings 搜索
Weak References in Manual Retain Release 改成Yes;
目前只能在xcode 9.x的版本上运xing,10.0以上会报错

前端

GCloudVoice.js

// 腾讯语音类
var GCloudVoice = {

    // ************************part:离线语音************************
    onSetForMsgClick() {
        console.log("-----设置离线语音");
        if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "enterMsgMode", "()V");
        } else if (cc.sys.os === cc.sys.OS_IOS && cc.sys.isBrowser !== true) {
            //设置语音模式,申请key
            console.log("申请key,模式");
            jsb.reflection.callStaticMethod("MessageViewController", "onApplyAuthKey");
        }
    },

    onGetKeyForMsgClick() {
        console.log("-----点击申请离线key");
        if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/gvoice/MsgActivity", "applyMsgKey", "()V");
        }
    },

    onOpenRecordForMsgClick() {
        console.log("-----点击打开录音状态");
        if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/gvoice/MsgActivity", "record", "()V");
        }
    },

    onStartRecordForMsgClick() {
        console.log("-----点击开始录音");
        if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/gvoice/RecordActivity", "startRecord", "()V");
        } else if (cc.sys.os === cc.sys.OS_IOS && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("MessageViewController", "startReCord:", G.uploadfilepath)
        }
    },

    //传送时间参数,可以自动播放使用
    onStopRecordForMsgClick(time) {
        console.log("-----点击停止录音");
        if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/gvoice/RecordActivity", "stopRecord", "(I)V", time);
        } else if (cc.sys.os === cc.sys.OS_IOS && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("MessageViewController", "stopReCord:andContent:", G.uploadfilepath, time)
        }
    },

    onOpenPlayForMsgClick(VoiceID, wxid) {
        cc.log("-----点击打开播放状态");
        if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/gvoice/MsgActivity", "play", "(Ljava/lang/String;I)V", VoiceID, wxid);
        }
    },

    onStartPlayForMsgClick(voiceID) {
        console.log("-----点击开始播放");
        if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/gvoice/PlayActivity", "startPlay", "()V");
        } else if (cc.sys.os === cc.sys.OS_IOS && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("MessageViewController", "onDownload:andContent:", voiceID, G.downloadfilepath)
        }
    },

    onStopPlayForMsgClick() {
        console.log("-----点击停止播放");
        if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/gvoice/PlayActivity", "stopPlay", "()V");
        } else if (cc.sys.os === cc.sys.OS_IOS && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("MessageViewController", "StopPlay")
        }
    },

    onDownloadPlayfile(str) {
        if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isBrowser !== true) {
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/gvoice/PlayActivity", "downloadPlayfile", "(Ljava/lang/String;)V", str);
        }
    },
};
module.exports = GCloudVoice;

本文地址:https://blog.csdn.net/chuying1509/article/details/107139535

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网