voiceBroadcast.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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. this.liveType = false;
  192. // console.log('取消', e)
  193. let moveLenght = e.touches[e.touches.length - 1].clientY - this.startPoint.clientY; //移动距离
  194. if (Math.abs(moveLenght) > 50) {
  195. uni.showToast({
  196. title: "松开手指,取消发送",
  197. icon: "none",
  198. duration: 60000
  199. });
  200. this.sendLock = true; //触发了上滑取消发送,上锁
  201. } else {
  202. uni.showToast({
  203. title: "正在录音,上划取消发送",
  204. icon: "none",
  205. duration: 60000
  206. });
  207. this.sendLock = false; //上划距离不足,依然可以发送,不上锁
  208. }
  209. },
  210. //发送
  211. sendButton(e) {
  212. // console.log("松开")
  213. let self = this;
  214. let num = 0;
  215. for (let i = 0; i < self.trumpetList.length; i++) {
  216. if (self.trumpetList[i].type) {
  217. num++
  218. }
  219. }
  220. if (num == 0) {
  221. return
  222. }
  223. this.liveType = false;
  224. // console.log('发送', e)
  225. uni.hideToast(); //结束录音、隐藏Toast提示框
  226. this.recorderManager.stop(); //结束录音
  227. this.recorderManager.onStop((res) => {
  228. if (!this.sendLock) {
  229. // console.log('1', this.recorderManager)
  230. // console.log('res.tempFilePath', res.tempFilePath)
  231. this.uploadImg(res.tempFilePath);
  232. }
  233. // console.log('停止录音', res.tempFilePath)
  234. // console.log("sendLock", this.sendLock);
  235. })
  236. },
  237. //上传MP3
  238. async uploadImg(tempFilePaths) {
  239. var self = this;
  240. uni.uploadFile({
  241. url: config.base_url + '/system/file/upload', //仅为示例,非真实的接口地址
  242. header: {
  243. 'Authorization': uni.getStorageSync('token')
  244. },
  245. filePath: tempFilePaths,
  246. name: 'file',
  247. formData: {
  248. 'user': 'test'
  249. },
  250. success: (uploadFileRes) => {
  251. let res = JSON.parse(uploadFileRes.data);
  252. if (res.code == 200) {
  253. // console.log("上传成功", res)
  254. let url = uni.getStorageSync('fileBrowseEnvironment') + '/' + res.data.url
  255. self.iotAppSpeakerPlayVoice(url);
  256. } else {
  257. uni.showToast({
  258. title: res.msg,
  259. icon: "none",
  260. mask: true,
  261. duration: 2000
  262. });
  263. }
  264. },
  265. fail: err => {
  266. uni.hideLoading()
  267. },
  268. complete: () => {}
  269. });
  270. },
  271. //发送语音
  272. async iotAppSpeakerPlayVoice(text) {
  273. let self = this;
  274. let list = [];
  275. for (let i = 0; i < self.trumpetList.length; i++) {
  276. if (self.trumpetList[i].type) {
  277. list.push(self.trumpetList[i].deviceNo)
  278. }
  279. }
  280. let obj = {
  281. deviceNo: list.join(','),
  282. voiceUrls: text,
  283. cycle: 1,
  284. level: 1000,
  285. }
  286. const {
  287. data
  288. } = await iotAppSpeakerPlayVoice(obj)
  289. if (data.code == 200) {
  290. uni.showToast({
  291. title: '发送成功',
  292. icon: "none",
  293. mask: true,
  294. duration: 2000
  295. });
  296. }
  297. },
  298. // #ifdef WEB
  299. /* H5 */
  300. async initRecorder() {
  301. try {
  302. // 获取麦克风权限
  303. const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  304. this.recorder = new Recorder({
  305. type: "mp3", // 输出格式
  306. bitRate: 128, // 比特率
  307. sampleRate: 44100 // 采样率
  308. });
  309. this.recorder.open(() => {
  310. // console.log("录音器初始化成功");
  311. this.recorder.start(); // 初始化后立即开始录音
  312. }, (error) => {
  313. console.error("录音器初始化失败:", error);
  314. uni.showToast({
  315. title: '麦克风权限获取失败,请允许麦克风权限',
  316. icon: "none",
  317. mask: true,
  318. duration: 2000
  319. });
  320. });
  321. } catch (err) {
  322. console.error("获取麦克风失败:", err);
  323. uni.showToast({
  324. title: '请允许麦克风权限',
  325. icon: "none",
  326. mask: true,
  327. duration: 2000
  328. });
  329. }
  330. },
  331. // 开始录音
  332. async startRecord() {
  333. let self = this;
  334. if (!this.recorder) {
  335. await this.initRecorder();
  336. // this.startRecord()
  337. return;
  338. }
  339. let num = 0;
  340. for (let i = 0; i < self.trumpetList.length; i++) {
  341. if (self.trumpetList[i].type) {
  342. num++
  343. }
  344. }
  345. if (num == 0) {
  346. uni.showToast({
  347. title: '请选择喇叭',
  348. icon: "none",
  349. mask: true,
  350. duration: 2000
  351. });
  352. return
  353. }
  354. this.recorder.start();
  355. this.recording = true;
  356. this.liveType = true;
  357. uni.showToast({ title: "录音开始", icon: "none" });
  358. },
  359. // 停止录音
  360. stopRecord() {
  361. if (!this.recorder || !this.recording) return;
  362. this.recorder.stop((blob, duration) => {
  363. this.recording = false;
  364. this.liveType = false;
  365. this.audioBlob = blob;
  366. // 生成临时文件路径
  367. this.audioPath = URL.createObjectURL(blob);
  368. this.uploadAudio();
  369. }, (error) => {
  370. console.error("录音失败:", error);
  371. uni.showToast({ title: "录音失败", icon: "none" });
  372. });
  373. },
  374. delRecord(){
  375. this.recorder.stop((blob, duration) => {
  376. this.recording = false;
  377. this.liveType = false;
  378. this.audioBlob = null;
  379. this.audioPath = null;
  380. })
  381. },
  382. // 上传录音文件
  383. uploadAudio() {
  384. let self = this;
  385. if (!this.audioBlob) return;
  386. // 1. 通过fetch获取Blob数据
  387. fetch(this.audioPath)
  388. .then(response => response.blob())
  389. .then(blob => {
  390. // 2. 将Blob转换为File对象
  391. const file = new File([blob], 'audio.mp3', { type: 'audio/mp3' });
  392. // console.log('file',file);
  393. // 3. 使用uni.uploadFile上传
  394. uni.uploadFile({
  395. url: config.base_url + '/system/file/upload',
  396. header: {
  397. 'Authorization': uni.getStorageSync('token')
  398. },
  399. file: file,
  400. name: 'file',
  401. formData: {
  402. 'user': 'test'
  403. },
  404. success: (res) => {
  405. // #ifdef WEB
  406. let obj = JSON.parse(res.data);
  407. // console.log('上传成功', obj);
  408. let url = uni.getStorageSync('fileBrowseEnvironment') + '/' + obj.data.url
  409. // #endif
  410. // #ifdef MP-WEIXIN
  411. // console.log('上传成功', res);
  412. let url = uni.getStorageSync('fileBrowseEnvironment') + '/' + res.data.url
  413. // #endif
  414. // console.log('url=====',url)
  415. self.iotAppSpeakerPlayVoice(url);
  416. },
  417. fail: (err) => {
  418. console.error('上传失败', err);
  419. uni.showToast({
  420. title: res.msg,
  421. icon: "none",
  422. mask: true,
  423. duration: 2000
  424. });
  425. }
  426. });
  427. })
  428. .catch(error => {
  429. console.error('获取Blob数据失败', error);
  430. });
  431. },
  432. //H5 拖拽
  433. // 触摸开始
  434. handleTouchStart(event) {
  435. // 彻底阻止所有默认行为
  436. event.preventDefault();
  437. event.stopPropagation();
  438. this.touchStartY = event.touches[0].clientY;
  439. this.hasMoved = false;
  440. this.moveDirection = null;
  441. this.hasTriggeredMethod3 = false;
  442. // 设置长按定时器
  443. this.longPressTimer = setTimeout(() => {
  444. this.isLongPress = true;
  445. this.startRecord(); // 执行方法1
  446. }, 300); // 300ms触发长按
  447. },
  448. // 触摸移动
  449. handleTouchMove(event) {
  450. // 彻底阻止所有默认行为
  451. event.preventDefault();
  452. event.stopPropagation();
  453. if (!this.isLongPress) return;
  454. const currentY = event.touches[0].clientY;
  455. const deltaY = currentY - this.touchStartY;
  456. // 检测滑动方向(向上滑动为负值)
  457. if (Math.abs(deltaY) > 75) { // 增加阈值避免误触
  458. this.hasMoved = true;
  459. this.moveDirection = deltaY < 0 ? 'up' : 'down';
  460. // 向上滑动执行方法3(确保只触发一次)
  461. if (this.moveDirection === 'up' && !this.hasTriggeredMethod3) {
  462. this.hasTriggeredMethod3 = true;
  463. this.delRecord();
  464. }
  465. }
  466. },
  467. // 触摸结束
  468. handleTouchEnd() {
  469. // 清除长按定时器
  470. clearTimeout(this.longPressTimer);
  471. if (this.isLongPress) {
  472. this.stopRecord(); // 执行方法2
  473. }
  474. // 重置状态
  475. this.isLongPress = false;
  476. this.hasMoved = false;
  477. this.moveDirection = null;
  478. },
  479. // 关键:禁用上下文菜单(长按菜单)
  480. handleContextMenu(e) {
  481. e.preventDefault();
  482. return false;
  483. },
  484. // #endif
  485. },
  486. beforeDestroy() {
  487. // 清理资源
  488. if (this.recorder) {
  489. this.recorder.close();
  490. }
  491. if (this.audioPath) {
  492. URL.revokeObjectURL(this.audioPath);
  493. }
  494. }
  495. }
  496. </script>
  497. <style lang="stylus" scoped>
  498. @import '@/api/request/imagesUrl.styl';
  499. .voiceBroadcast {
  500. height: 100%;
  501. width: 100%;
  502. position: fixed;
  503. top: 0;
  504. display: flex;
  505. flex-direction: column;
  506. z-index: 10;
  507. background: rgba(0, 0, 0, 0.2);
  508. .null-box {
  509. flex: 1;
  510. }
  511. /* 语音广播-执行疏散 */
  512. .broadcast {
  513. width: 100%;
  514. background: #FFFFFF;
  515. border-top-left-radius: 20rpx;
  516. border-top-right-radius: 20rpx;
  517. padding: 22rpx 30rpx 30rpx;
  518. box-sizing: border-box;
  519. margin-top: 20rpx;
  520. position: absolute;
  521. bottom: 0;
  522. .broadcast_t {
  523. font-size: 30rpx;
  524. font-family: PingFang SC;
  525. font-weight: 500;
  526. color: #333333;
  527. line-height: 30rpx;
  528. >label {
  529. font-size: 24rpx;
  530. font-family: PingFang SC;
  531. font-weight: 500;
  532. color: #999999;
  533. line-height: 30rpx;
  534. margin-left: 16rpx;
  535. }
  536. }
  537. .trumpet-max-box {
  538. display: flex;
  539. justify-content: flex-start;
  540. margin-top: 22rpx;
  541. flex-wrap: wrap;
  542. .trumpet-for-box {
  543. display: inline-block;
  544. width: auto;
  545. height: 60rpx;
  546. line-height: 60rpx;
  547. font-size: 24rpx;
  548. text-align: center;
  549. cursor: pointer;
  550. overflow: hidden;
  551. border: 1rpx solid #E0E0E0;
  552. border-radius: 10rpx;
  553. color: #E0E0E0;
  554. display: flex;
  555. justify-content: center;
  556. margin-right: 20rpx;
  557. margin-bottom: 10rpx;
  558. padding: 0 12rpx;
  559. box-sizing: border-box;
  560. >img {
  561. width: 36rpx;
  562. height: 34rpx;
  563. margin: 12rpx 20rpx 0 25rpx;
  564. }
  565. }
  566. .trumpet-color-a {
  567. border: 1px solid #0183FA;
  568. color: #0183FA;
  569. }
  570. .trumpet-color-b {
  571. border: 1px solid #CCCCCC;
  572. color: #999;
  573. }
  574. }
  575. .no-long-press{
  576. // -webkit-touch-callout: none !important;
  577. // -webkit-user-select: none !important;
  578. // -khtml-user-select: none !important;
  579. // -moz-user-select: none !important;
  580. // -ms-user-select: none !important;
  581. // user-select: none !important;
  582. }
  583. .broadcast_m {
  584. width: 100%;
  585. .broadcast_m_t {
  586. width: 142rpx;
  587. height: 142rpx;
  588. margin: 30rpx 0 0 258rpx;
  589. position: relative;
  590. font-size: 24rpx;
  591. font-family: PingFang SC;
  592. font-weight: 500;
  593. line-height: 170rpx;
  594. text-align: center;
  595. >img {
  596. width: 142rpx;
  597. height: 142rpx;
  598. position: absolute;
  599. }
  600. >label {
  601. width: 100%;
  602. font-size: 24rpx;
  603. font-family: PingFang SC;
  604. font-weight: 500;
  605. color: #0183FA;
  606. line-height: 24rpx;
  607. display: inline-block;
  608. text-align: center;
  609. position: absolute;
  610. top: 76rpx;
  611. }
  612. /* 按下 */
  613. .press_color {
  614. color: #FFFFFF;
  615. }
  616. /* 松开 */
  617. .slip_color {
  618. color: #0183FA;
  619. }
  620. }
  621. .broadcast_m_b {
  622. font-size: 24rpx;
  623. font-family: PingFang SC;
  624. font-weight: 500;
  625. color: #999999;
  626. line-height: 24rpx;
  627. text-align: center;
  628. margin-top: 14rpx;
  629. }
  630. .broadcast_m_t_back_a {
  631. background: url($imagesUrl+'commonality/icon_sskz_skfs_1.png') no-repeat center 0px;
  632. background-size: 100%;
  633. color: #FFFFFF;
  634. }
  635. .broadcast_m_t_back_b {
  636. background: url($imagesUrl+'commonality/icon_sskz_azsh_1.png') no-repeat center 0px;
  637. background-size: 100%;
  638. color: #0183FA;
  639. }
  640. }
  641. /* 疏散按钮 */
  642. .evacuation-button-box {
  643. width: 650rpx;
  644. height: 100rpx;
  645. background: #0183FA;
  646. color: #fff;
  647. text-align center;
  648. line-height: 100rpx;
  649. font-size: 28rpx;
  650. margin: 88rpx auto 0;
  651. border-radius: 20rpx;
  652. }
  653. }
  654. }
  655. </style>