voiceBroadcast.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. <!-- 语音广播 -->
  2. <template>
  3. <view class="voiceBroadcast">
  4. <view class="null-box" @click="backPage()"></view>
  5. <!-- 语音广播-执行疏散 -->
  6. <view class="broadcast">
  7. <view class="broadcast_t">语音广播<label>选择喇叭位置</label></view>
  8. <!-- 按钮部分 -->
  9. <view class="trumpet-max-box">
  10. <view @click="trumpetClick(index)" class="trumpet-for-box"
  11. :class="item.type?'trumpet-color-a':'trumpet-color-b'" v-for="(item,index) in trumpetList" :key="index">
  12. <img :src="imagesUrl('commonality/icon_sskz_zc.png')" v-if="!item.type">
  13. <img :src="imagesUrl('commonality/icon_sskz_xz.png')" v-if="item.type">
  14. {{item.deviceName}}
  15. </view>
  16. </view>
  17. <!-- #ifdef MP-WEIXIN -->
  18. <view class="broadcast_m">
  19. <view class="broadcast_m_t" :class="liveType?'broadcast_m_t_back_a':'broadcast_m_t_back_b'"
  20. @longpress.stop="recordButton" @touchmove.stop="cancelButton" @touchend.stop="sendButton">
  21. {{liveType?'松开发送':'按住说话'}}
  22. </view>
  23. <view class="broadcast_m_b" v-if="!liveType">按住说话,录入广播内容</view>
  24. <view class="broadcast_m_b" v-if="liveType">松开发送,向上滑动取消发送</view>
  25. </view>
  26. <!-- #endif -->
  27. <!-- #ifdef WEB -->
  28. <view class="broadcast_m no-long-press">
  29. <view class="broadcast_m_t no-long-press"
  30. :class="liveType?'broadcast_m_t_back_a':'broadcast_m_t_back_b'"
  31. @touchstart="handleTouchStart"
  32. @touchmove="handleTouchMove"
  33. @touchend="handleTouchEnd"
  34. @touchcancel="handleTouchEnd"
  35. @contextmenu.prevent="handleContextMenu">
  36. </view>
  37. <!-- @longpress.stop="startRecord" @touchmove.stop="delRecord" @touchend.stop="stopRecord" -->
  38. <view class="broadcast_m_b no-long-press" v-if="!liveType">按住说话,录入广播内容</view>
  39. <view class="broadcast_m_b no-long-press" v-if="liveType">松开发送,向上滑动取消发送</view>
  40. </view>
  41. <!-- #endif -->
  42. </view>
  43. </view>
  44. </template>
  45. <script>
  46. // #ifdef WEB
  47. import Recorder from 'recorder-core';
  48. import 'recorder-core/src/engine/mp3';
  49. import 'recorder-core/src/engine/mp3-engine';
  50. // #endif
  51. import {
  52. iotAppSpeakerFindHorn,
  53. iotAppSpeakerPlayVoice
  54. } from '@/pages_manage/api/index.js'
  55. import {
  56. config
  57. } from '@/api/request/config.js'
  58. export default {
  59. name: "voiceBroadcast",
  60. props: {
  61. subjectData: {},
  62. },
  63. data() {
  64. return {
  65. baseUrl: config.base_url,
  66. //喇叭数据
  67. trumpetList: [],
  68. //广播相关
  69. liveType: false,
  70. sendLock: true, //发送锁,当为true时上锁,false时解锁发送
  71. recorderManager: uni.getRecorderManager(),
  72. isEvacuate: true, //疏散按钮控制,当为true时候执行疏散
  73. //滑动记录
  74. startPoint: {},
  75. subId: '',
  76. floorId: '',
  77. //H5
  78. recording: false,
  79. recorder: null,
  80. audioBlob: null,
  81. audioPath: null,
  82. //H5 拖拽
  83. touchStartY: 0,
  84. isLongPress: false,
  85. hasMoved: false,
  86. longPressTimer: null,
  87. moveDirection: null,
  88. hasTriggeredMethod3: false, // 确保方法3只触发一次
  89. }
  90. },
  91. created() {
  92. },
  93. mounted() {
  94. this.$set(this, 'subId', this.subjectData.subId);
  95. this.$set(this, 'floorId', this.subjectData.floorId);
  96. this.iotAppSpeakerFindHorn();
  97. // #ifdef WEB
  98. if (this.recorderManager) {
  99. this.recorderManager.stop();
  100. }
  101. // #endif
  102. },
  103. methods: {
  104. // 返回按钮
  105. backPage() {
  106. // #ifdef WEB
  107. this.$parent.$parent.buttonClick('broadcastClose', '');
  108. // #endif
  109. // #ifdef MP-WEIXIN
  110. this.$parent.buttonClick('broadcastClose', '');
  111. // #endif
  112. },
  113. //获取喇叭列表
  114. async iotAppSpeakerFindHorn() {
  115. let self = this;
  116. let obj = {
  117. subId: self.subId,
  118. floorId: self.floorId,
  119. };
  120. const {
  121. data
  122. } = await iotAppSpeakerFindHorn(obj)
  123. if (data.code == 200) {
  124. for (let i = 0; i < data.data.length; i++) {
  125. data.data[i].type = false;
  126. }
  127. this.$set(this, 'trumpetList', data.data)
  128. }
  129. },
  130. //点击选择喇叭
  131. trumpetClick(index) {
  132. this.trumpetList[index].type = !this.trumpetList[index].type;
  133. },
  134. //录制
  135. recordButton(e) {
  136. console.log("按下")
  137. let self = this;
  138. let num = 0;
  139. for (let i = 0; i < self.trumpetList.length; i++) {
  140. if (self.trumpetList[i].type) {
  141. num++
  142. }
  143. }
  144. if (num == 0) {
  145. uni.showToast({
  146. title: '请选择喇叭',
  147. icon: "none",
  148. mask: true,
  149. duration: 2000
  150. });
  151. return
  152. }
  153. this.liveType = true;
  154. // console.log('录制', e)
  155. this.startPoint = e.touches[0]; //记录长按时开始点信息,后面用于计算上划取消时手指滑动的距离。
  156. const options = {
  157. duration: 10000,
  158. sampleRate: 16000,
  159. numberOfChannels: 1,
  160. encodeBitRate: 48000,
  161. format: 'mp3',
  162. frameSize: 50
  163. }
  164. this.recorderManager.start(options); //开始录音
  165. this.recorderManager.onStart(() => {
  166. // console.log('recorder start')
  167. })
  168. this.recorderManager.onError((res) => {
  169. // console.log(res);
  170. })
  171. uni.showToast({
  172. title: "正在录音,上划取消发送",
  173. icon: "none",
  174. duration: 60000 //先定义个60秒,后面可以手动调用wx.hideToast()隐藏
  175. });
  176. this.sendLock = false; //长按时是不上锁的。
  177. },
  178. //取消
  179. cancelButton(e) {
  180. // console.log("移动")
  181. let self = this;
  182. let num = 0;
  183. for (let i = 0; i < self.trumpetList.length; i++) {
  184. if (self.trumpetList[i].type) {
  185. num++
  186. }
  187. }
  188. if (num == 0) {
  189. return
  190. }
  191. // console.log('取消', e)
  192. let moveLenght = e.touches[e.touches.length - 1].clientY - this.startPoint.clientY; //移动距离
  193. if (Math.abs(moveLenght) > 50) {
  194. uni.showToast({
  195. title: "松开手指,取消发送",
  196. icon: "none",
  197. duration: 60000
  198. });
  199. this.liveType = false;
  200. this.sendLock = true; //触发了上滑取消发送,上锁
  201. } else {
  202. uni.showToast({
  203. title: "正在录音,上划取消发送",
  204. icon: "none",
  205. duration: 60000
  206. });
  207. this.liveType = true;
  208. this.sendLock = false; //上划距离不足,依然可以发送,不上锁
  209. }
  210. },
  211. //发送
  212. sendButton(e) {
  213. // console.log("松开")
  214. let self = this;
  215. let num = 0;
  216. for (let i = 0; i < self.trumpetList.length; i++) {
  217. if (self.trumpetList[i].type) {
  218. num++
  219. }
  220. }
  221. if (num == 0) {
  222. return
  223. }
  224. this.liveType = false;
  225. // console.log('发送', e)
  226. uni.hideToast(); //结束录音、隐藏Toast提示框
  227. this.recorderManager.stop(); //结束录音
  228. this.recorderManager.onStop((res) => {
  229. if (!this.sendLock) {
  230. // console.log('1', this.recorderManager)
  231. // console.log('res.tempFilePath', res.tempFilePath)
  232. this.uploadImg(res.tempFilePath);
  233. }
  234. // console.log('停止录音', res.tempFilePath)
  235. // console.log("sendLock", this.sendLock);
  236. })
  237. },
  238. //上传MP3
  239. async uploadImg(tempFilePaths) {
  240. var self = this;
  241. uni.uploadFile({
  242. url: config.base_url + '/system/file/upload', //仅为示例,非真实的接口地址
  243. header: {
  244. 'Authorization': uni.getStorageSync('token')
  245. },
  246. filePath: tempFilePaths,
  247. name: 'file',
  248. formData: {
  249. 'user': 'test'
  250. },
  251. success: (uploadFileRes) => {
  252. let res = JSON.parse(uploadFileRes.data);
  253. if (res.code == 200) {
  254. // console.log("上传成功", res)
  255. let url = uni.getStorageSync('fileBrowseEnvironment') + '/' + res.data.url
  256. self.iotAppSpeakerPlayVoice(url);
  257. } else {
  258. uni.showToast({
  259. title: res.msg,
  260. icon: "none",
  261. mask: true,
  262. duration: 2000
  263. });
  264. }
  265. },
  266. fail: err => {
  267. uni.hideLoading()
  268. },
  269. complete: () => {}
  270. });
  271. },
  272. //发送语音
  273. async iotAppSpeakerPlayVoice(text) {
  274. let self = this;
  275. let list = [];
  276. for (let i = 0; i < self.trumpetList.length; i++) {
  277. if (self.trumpetList[i].type) {
  278. list.push(self.trumpetList[i].deviceNo)
  279. }
  280. }
  281. let obj = {
  282. deviceNo: list.join(','),
  283. voiceUrls: text,
  284. cycle: 1,
  285. level: 1000,
  286. }
  287. const {
  288. data
  289. } = await iotAppSpeakerPlayVoice(obj)
  290. if (data.code == 200) {
  291. uni.showToast({
  292. title: '发送成功',
  293. icon: "none",
  294. mask: true,
  295. duration: 2000
  296. });
  297. }
  298. },
  299. // #ifdef WEB
  300. /* H5 */
  301. async initRecorder() {
  302. try {
  303. // 获取麦克风权限
  304. await navigator.mediaDevices.getUserMedia({ audio: true });
  305. this.recorder = new Recorder({
  306. type: "mp3", // 输出格式
  307. bitRate: 64, // 降低比特率提升兼容性
  308. // 不指定 sampleRate,让浏览器使用系统默认值(iOS 兼容性要求)
  309. });
  310. this.recorder.open(() => {
  311. // 初始化成功,继续 startRecord 流程
  312. this.startRecord();
  313. }, (error) => {
  314. console.error("录音器初始化失败:", error);
  315. uni.showToast({
  316. title: '麦克风权限获取失败,请允许麦克风权限',
  317. icon: "none",
  318. mask: true,
  319. duration: 2000
  320. });
  321. });
  322. } catch (err) {
  323. console.error("获取麦克风失败:", err);
  324. uni.showToast({
  325. title: '请允许麦克风权限',
  326. icon: "none",
  327. mask: true,
  328. duration: 2000
  329. });
  330. }
  331. },
  332. // 开始录音
  333. async startRecord() {
  334. let self = this;
  335. if (!this.recorder) {
  336. await this.initRecorder();
  337. // this.startRecord()
  338. return;
  339. }
  340. let num = 0;
  341. for (let i = 0; i < self.trumpetList.length; i++) {
  342. if (self.trumpetList[i].type) {
  343. num++
  344. }
  345. }
  346. if (num == 0) {
  347. uni.showToast({
  348. title: '请选择喇叭',
  349. icon: "none",
  350. mask: true,
  351. duration: 2000
  352. });
  353. return
  354. }
  355. this.recorder.start();
  356. this.recording = true;
  357. this.liveType = true;
  358. uni.showToast({ title: "录音开始", icon: "none" });
  359. },
  360. // 停止录音
  361. stopRecord() {
  362. if (!this.recorder || !this.recording) return;
  363. this.recorder.stop((blob, duration) => {
  364. this.recording = false;
  365. this.liveType = false;
  366. this.audioBlob = blob;
  367. // 生成临时文件路径
  368. this.audioPath = URL.createObjectURL(blob);
  369. this.uploadAudio();
  370. }, (error) => {
  371. console.error("录音失败:", error);
  372. uni.showToast({ title: "录音失败", icon: "none" });
  373. });
  374. },
  375. delRecord(){
  376. this.recorder.stop((blob, duration) => {
  377. this.recording = false;
  378. this.liveType = false;
  379. this.audioBlob = null;
  380. this.audioPath = null;
  381. })
  382. },
  383. // 上传录音文件
  384. uploadAudio() {
  385. let self = this;
  386. if (!this.audioBlob) return;
  387. // 1. 通过fetch获取Blob数据
  388. fetch(this.audioPath)
  389. .then(response => response.blob())
  390. .then(blob => {
  391. // 2. 将Blob转换为File对象
  392. const file = new File([blob], 'audio.mp3', { type: 'audio/mp3' });
  393. // console.log('file',file);
  394. // 3. 使用uni.uploadFile上传
  395. uni.uploadFile({
  396. url: config.base_url + '/system/file/upload',
  397. header: {
  398. 'Authorization': uni.getStorageSync('token')
  399. },
  400. file: file,
  401. name: 'file',
  402. formData: {
  403. 'user': 'test'
  404. },
  405. success: (res) => {
  406. // #ifdef WEB
  407. let obj = JSON.parse(res.data);
  408. // console.log('上传成功', obj);
  409. let url = uni.getStorageSync('fileBrowseEnvironment') + '/' + obj.data.url
  410. // #endif
  411. // #ifdef MP-WEIXIN
  412. // console.log('上传成功', res);
  413. let url = uni.getStorageSync('fileBrowseEnvironment') + '/' + res.data.url
  414. // #endif
  415. // console.log('url=====',url)
  416. self.iotAppSpeakerPlayVoice(url);
  417. },
  418. fail: (err) => {
  419. console.error('上传失败', err);
  420. uni.showToast({
  421. title: res.msg,
  422. icon: "none",
  423. mask: true,
  424. duration: 2000
  425. });
  426. }
  427. });
  428. })
  429. .catch(error => {
  430. console.error('获取Blob数据失败', error);
  431. });
  432. },
  433. //H5 拖拽
  434. // 触摸开始
  435. handleTouchStart(event) {
  436. // 彻底阻止所有默认行为
  437. event.preventDefault();
  438. event.stopPropagation();
  439. this.touchStartY = event.touches[0].clientY;
  440. this.hasMoved = false;
  441. this.moveDirection = null;
  442. this.hasTriggeredMethod3 = false;
  443. // 设置长按定时器
  444. this.longPressTimer = setTimeout(() => {
  445. this.isLongPress = true;
  446. this.startRecord(); // 执行方法1
  447. }, 300); // 300ms触发长按
  448. },
  449. // 触摸移动
  450. handleTouchMove(event) {
  451. // 彻底阻止所有默认行为
  452. event.preventDefault();
  453. event.stopPropagation();
  454. if (!this.isLongPress) return;
  455. const currentY = event.touches[0].clientY;
  456. const deltaY = currentY - this.touchStartY;
  457. // 检测滑动方向(向上滑动为负值)
  458. if (Math.abs(deltaY) > 75) { // 增加阈值避免误触
  459. this.hasMoved = true;
  460. this.moveDirection = deltaY < 0 ? 'up' : 'down';
  461. // 向上滑动执行方法3(确保只触发一次)
  462. if (this.moveDirection === 'up' && !this.hasTriggeredMethod3) {
  463. this.hasTriggeredMethod3 = true;
  464. this.delRecord();
  465. }
  466. }
  467. },
  468. // 触摸结束
  469. handleTouchEnd() {
  470. // 清除长按定时器
  471. clearTimeout(this.longPressTimer);
  472. if (this.isLongPress) {
  473. this.stopRecord(); // 执行方法2
  474. }
  475. // 重置状态
  476. this.isLongPress = false;
  477. this.hasMoved = false;
  478. this.moveDirection = null;
  479. },
  480. // 关键:禁用上下文菜单(长按菜单)
  481. handleContextMenu(e) {
  482. e.preventDefault();
  483. return false;
  484. },
  485. // #endif
  486. },
  487. beforeDestroy() {
  488. // 清理资源
  489. if (this.recorder) {
  490. this.recorder.close();
  491. }
  492. if (this.audioPath) {
  493. URL.revokeObjectURL(this.audioPath);
  494. }
  495. }
  496. }
  497. </script>
  498. <style lang="stylus" scoped>
  499. @import '@/api/request/imagesUrl.styl';
  500. .voiceBroadcast {
  501. height: 100%;
  502. width: 100%;
  503. position: fixed;
  504. top: 0;
  505. display: flex;
  506. flex-direction: column;
  507. z-index: 10;
  508. background: rgba(0, 0, 0, 0.2);
  509. .null-box {
  510. flex: 1;
  511. }
  512. /* 语音广播-执行疏散 */
  513. .broadcast {
  514. width: 100%;
  515. background: #FFFFFF;
  516. border-top-left-radius: 20rpx;
  517. border-top-right-radius: 20rpx;
  518. padding: 22rpx 30rpx 30rpx;
  519. box-sizing: border-box;
  520. margin-top: 20rpx;
  521. position: absolute;
  522. bottom: 0;
  523. .broadcast_t {
  524. font-size: 30rpx;
  525. font-family: PingFang SC;
  526. font-weight: 500;
  527. color: #333333;
  528. line-height: 30rpx;
  529. >label {
  530. font-size: 24rpx;
  531. font-family: PingFang SC;
  532. font-weight: 500;
  533. color: #999999;
  534. line-height: 30rpx;
  535. margin-left: 16rpx;
  536. }
  537. }
  538. .trumpet-max-box {
  539. display: flex;
  540. justify-content: flex-start;
  541. margin-top: 22rpx;
  542. flex-wrap: wrap;
  543. .trumpet-for-box {
  544. display: inline-block;
  545. width: auto;
  546. height: 60rpx;
  547. line-height: 60rpx;
  548. font-size: 24rpx;
  549. text-align: center;
  550. cursor: pointer;
  551. overflow: hidden;
  552. border: 1rpx solid #E0E0E0;
  553. border-radius: 10rpx;
  554. color: #E0E0E0;
  555. display: flex;
  556. justify-content: center;
  557. margin-right: 20rpx;
  558. margin-bottom: 10rpx;
  559. padding: 0 12rpx;
  560. box-sizing: border-box;
  561. >img {
  562. width: 36rpx;
  563. height: 34rpx;
  564. margin: 12rpx 20rpx 0 25rpx;
  565. }
  566. }
  567. .trumpet-color-a {
  568. border: 1px solid #0183FA;
  569. color: #0183FA;
  570. }
  571. .trumpet-color-b {
  572. border: 1px solid #CCCCCC;
  573. color: #999;
  574. }
  575. }
  576. .no-long-press{
  577. // -webkit-touch-callout: none !important;
  578. // -webkit-user-select: none !important;
  579. // -khtml-user-select: none !important;
  580. // -moz-user-select: none !important;
  581. // -ms-user-select: none !important;
  582. // user-select: none !important;
  583. }
  584. .broadcast_m {
  585. width: 100%;
  586. .broadcast_m_t {
  587. width: 142rpx;
  588. height: 142rpx;
  589. margin: 30rpx 0 0 258rpx;
  590. position: relative;
  591. font-size: 24rpx;
  592. font-family: PingFang SC;
  593. font-weight: 500;
  594. line-height: 170rpx;
  595. text-align: center;
  596. >img {
  597. width: 142rpx;
  598. height: 142rpx;
  599. position: absolute;
  600. }
  601. >label {
  602. width: 100%;
  603. font-size: 24rpx;
  604. font-family: PingFang SC;
  605. font-weight: 500;
  606. color: #0183FA;
  607. line-height: 24rpx;
  608. display: inline-block;
  609. text-align: center;
  610. position: absolute;
  611. top: 76rpx;
  612. }
  613. /* 按下 */
  614. .press_color {
  615. color: #FFFFFF;
  616. }
  617. /* 松开 */
  618. .slip_color {
  619. color: #0183FA;
  620. }
  621. }
  622. .broadcast_m_b {
  623. font-size: 24rpx;
  624. font-family: PingFang SC;
  625. font-weight: 500;
  626. color: #999999;
  627. line-height: 24rpx;
  628. text-align: center;
  629. margin-top: 14rpx;
  630. }
  631. .broadcast_m_t_back_a {
  632. background: url($imagesUrl+'commonality/icon_sskz_skfs_1.png') no-repeat center 0px;
  633. background-size: 100%;
  634. color: #FFFFFF;
  635. }
  636. .broadcast_m_t_back_b {
  637. background: url($imagesUrl+'commonality/icon_sskz_azsh_1.png') no-repeat center 0px;
  638. background-size: 100%;
  639. color: #0183FA;
  640. }
  641. }
  642. /* 疏散按钮 */
  643. .evacuation-button-box {
  644. width: 650rpx;
  645. height: 100rpx;
  646. background: #0183FA;
  647. color: #fff;
  648. text-align center;
  649. line-height: 100rpx;
  650. font-size: 28rpx;
  651. margin: 88rpx auto 0;
  652. border-radius: 20rpx;
  653. }
  654. }
  655. }
  656. </style>