1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
| cc.Class({ extends: require('baseView'), statics: { show: function () { let bundle = cc.assetManager.getBundle(BUNDLEENUM.FISHGAME); if (!bundle) { cc.error("not find the bundle " + BUNDLEENUM.FISHGAME); return; } let bname = "pop/chat/chatView"; bundle.load(bname, cc.Prefab, function (err, prefab) { if (err) return; let chatView = cc.director.getScene().getChildByName("chatView"); if (chatView && cc.isValid(chatView)) return; if (prefab && prefab instanceof cc.Prefab) { let alert = cc.instantiate(prefab); cc.director.getScene().addChild(alert); alert.name = 'chatView'; alert.setPosition(cc.view.getVisibleSize().width / 2, cc.view.getVisibleSize().height / 2); alert.zIndex = cc.vv.global.ALERT_LAYER; } }); }, }, properties: { content: cc.Node, chatItem : cc.Node, editBox : cc.EditBox, recordButton : cc.Button, chat_shuo : cc.Node, }, onLoad: function () { if (cc.vv.resMgr.getCurSceneName() != SCENES_TYPE.FISHGAME) { this.node.destroy(); return; } this.chatItem.removeFromParent(); this.recordButton.node.on(cc.Node.EventType.TOUCH_START, this.startRecording, this); this.recordButton.node.on(cc.Node.EventType.TOUCH_END, this.stopRecording, this); this.recordButton.node.on(cc.Node.EventType.TOUCH_CANCEL, this.stopRecording, this); this.start_voice = false; this.chat_shuo.active = false; this.voice_time = 15; this.bgm_v = cc.vv.audioMgr.bgmVolume; this.sfx_v = cc.vv.audioMgr.sfxVolume; this.mediaRecorder; this.audioChunks = []; this.start_time = 0; this.stop_time = 0; }, start(){ for (let index = 0; index < cc.vv.global.FISH_TXTS.length; index++) { const text = cc.vv.global.FISH_TXTS[index]; let item = cc.instantiate(this.chatItem); item.parent = this.content; item.info = text; let richtext = item.getComponentInChildren(cc.RichText); richtext.string = text; } }, async getMicrophoneStream() { try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); return stream; } catch (error) { console.error("获取麦克风失败:", error); return null; } }, //开始录音 startRecording() { if (cc.sys.isBrowser) { if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { // console.error("当前浏览器不支持 getUserMedia()"); require("updateTips").show("亲爱的客户\n您当前浏览器不支持使用语音功能\n请下载安装包,安装后再使用"); return; } console.log("请求麦克风权限..."); this.audioChunks = []; if (this.mediaRecorder) { this.mediaRecorder.stop(); this.mediaRecorder = null; } navigator.mediaDevices.getUserMedia({ audio: true }) .then((stream) => { if (!(stream instanceof MediaStream)) { console.error("获取的不是 MediaStream:", stream); return; } console.log("麦克风权限获取成功:", stream); // **确保 mediaRecorder 重新创建** this.mediaRecorder = new MediaRecorder(stream); this.mediaRecorder.ondataavailable = (event) => { if (event.data.size > 0) { this.audioChunks.push(event.data); } }; this.mediaRecorder.onstop = async () => { console.log("录音结束, 开始处理音频..."); // 录音结束时调用 this.processAudioData(this.audioChunks); }; this.mediaRecorder.start(); console.log("录音开始..."); }) .catch((error) => { console.error("无法获取麦克风权限:", error); }); // return; } if(cc.vv.utils.isChatApkUpdate()) { require("updateTips").show("亲爱的客户\n您现在版本太低无法使用语音功能\n请下载最新版本,安装后再使用"); return; } // 调用 Android 原生方法开始录音 if (this.start_voice) { return; } this.bgm_v = cc.vv.audioMgr.bgmVolume; this.sfx_v = cc.vv.audioMgr.sfxVolume; cc.vv.audioMgr.setBGMVolume(0); cc.vv.audioMgr.setSFXVolume(0); this.voice_time = 15; this.start_voice = true; this.chat_shuo.active = true; this.chat_shuo.stopAllActions(); this.chat_shuo.getComponent(sp.Skeleton).clearTracks(); this.chat_shuo.getComponent(sp.Skeleton).setAnimation(0,"animation",true); this.chat_shuo.runAction(cc.repeatForever(cc.sequence([cc.callFunc(()=>{ if (this.voice_time < 0) { this.chat_shuo.stopAllActions(); this.stopRecording(); return; } this.chat_shuo.getChildByName("lab").getComponent(cc.Label).string = this.voice_time; this.voice_time--; }) , cc.delayTime(1)]))); cc.vv.device.startRecording(); this.start_time = new Date().getTime(); }, stopRecording() { if (cc.sys.isBrowser) { if (this.mediaRecorder) { this.mediaRecorder.stop(); // cc.error("录音结束..."); } // return; } // 调用 Android 原生方法停止录音并返回音频数据 if (this.start_voice == false) { return; } cc.vv.audioMgr.setBGMVolume(this.bgm_v); cc.vv.audioMgr.setSFXVolume(this.sfx_v); cc.error("stopRecording"); this.start_voice = false; this.chat_shuo.active = false; cc.vv.device.stopRecording(); this.stop_time = new Date().getTime(); }, async processAudioData(audioChunks) { const audioBlob = new Blob(audioChunks, { type: "audio/wav" }); const audioContext = new AudioContext(); const reader = new FileReader(); reader.readAsArrayBuffer(audioBlob); reader.onloadend = async () => { try { const audioBuffer = await audioContext.decodeAudioData(reader.result); const sampleRate = 44100; // 统一降采样 const mp3Encoder = new lamejs.Mp3Encoder(1, sampleRate, 128); // 修正 samples 计算 const samples = new Int16Array(audioBuffer.getChannelData(0).map(n => Math.round(n * 32767))); const mp3Data = []; const sampleBlockSize = 1152; for (let i = 0; i < samples.length; i += sampleBlockSize) { const sampleBlock = samples.subarray(i, Math.min(i + sampleBlockSize, samples.length)); const mp3Block = mp3Encoder.encodeBuffer(sampleBlock); mp3Data.push(mp3Block); } const finalMp3Block = mp3Encoder.flush(); mp3Data.push(finalMp3Block); const mp3Blob = new Blob(mp3Data, { type: 'audio/mp3' }); let duration = this.stop_time - this.start_time; // cc.error("duration",duration); // 转换 Base64 this.convertBlobToBase64(mp3Blob,(base64Audio)=>{ // cc.error("MP3 Base64 编码:", base64Audio); // 发送数据 if (cc.vv.gameRequest) { const chunkSize = 51200; if (base64Audio.length > chunkSize) { let chunks = Math.ceil(base64Audio.length / chunkSize); for (let i = 0; i < chunks; i++) { let chunk = base64Audio.slice(i * chunkSize, (i + 1) * chunkSize); cc.vv.gameRequest.sendChatReq(4, "", duration, chunk, i + "", chunks); // cc.error("Sending chunk: ", i + 1, " / ", chunks); } } else { cc.vv.gameRequest.sendChatReq(4, "", duration, base64Audio); } } }); } catch (error) { console.error("解码音频数据失败:", error); } }; }, /** * 将 Blob 转换为 Base64 */ convertBlobToBase64(blob, callback) { const reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = () => { const base64String = reader.result.split(',')[1]; // 去掉 Data URL 头部信息 callback(base64String); }; }, // 下载 MP3 文件 downloadMp3(mp3Blob) { const mp3Url = URL.createObjectURL(mp3Blob); const downloadLink = document.createElement('a'); downloadLink.href = mp3Url; downloadLink.download = 'audio.mp3'; downloadLink.click(); }, // 播放 MP3 playMp3(mp3Data) { if (!mp3Data || !(mp3Data instanceof Blob)) { console.error("MP3 数据无效:", mp3Data); return; } const audioURL = URL.createObjectURL(mp3Data); const audio = new Audio(audioURL); audio.play(); }, showView(){ this.node.active = true; }, // Base64 转 Uint8Array base64ToUint8Array(base64Str) { let binary = atob(base64Str); let len = binary.length; let bytes = new Uint8Array(len); for (let i = 0; i < len; i++) { bytes[i] = binary.charCodeAt(i); } return bytes; }, onItemClicked(event, type){ let text = event.target.info; this.sendChat(text); this.hidePanel(); }, onBtnClicked(event, type) { if (cc.vv.utils.allowclick(0.3) == false) { return; } let name = event.target.name; if (name == "backbtn") { this.hidePanel(); } else if (name == "btn_send") { let text = this.editBox.string; if (text) { // let test = ""; // for (let index = 0; index < 1024*50; index++) { // test +="A"; // } // cc.error("test",test.length); // 51200 if (text.length > 15) { require("Tips").show("老板,发送内容太长了,请修改!"); return; } cc.vv.gameRequest.sendChatReq(1, text); this.editBox.string = ""; this.hidePanel(); } else { require("Tips").show("请输入要发送的文字..."); } } }, sendChat(text){ cc.vv.gameRequest.sendChatReq(1, text); }, onDestroy() { if (signal) signal.targetOff(this); this.chatItem.destroy(); if (this.start_voice) { this.stopRecording(); } }, });
|