readContent.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <!-- 单词区 && 音标区:最多16位,超过换行 -->
  2. <!-- 单音节最长:swimming 多音节最长:transportation -->
  3. <template>
  4. <selectTypesVue activeSelect="3"></selectTypesVue>
  5. <view class="ezy-border-body">
  6. <view class="words-du-box">
  7. <view class="du-body-box">
  8. <!-- 单词区 -->
  9. <view class="word-circle-box">{{data.name}}</view>
  10. <!-- 音标区 -->
  11. <view class="yb-play-box du-yb-play-box">
  12. <yinbiaoTxtVue :yinbiao="activeWord.yinbiao"></yinbiaoTxtVue>
  13. <!-- 音频播放 -->
  14. <audioTwoVue :active-word="activeWord" @play-audio="handlePlay"></audioTwoVue>
  15. </view>
  16. <view class="pin-words-explain-box du-words-explain-box">
  17. <view class="words-explain-item" v-if="data.jianyi&&data.jianyi.length>0"
  18. v-for="(item,index) in data.jianyi" :key="index">
  19. {{item}}
  20. </view>
  21. </view>
  22. </view>
  23. <view class="mike-play-box">
  24. <view class="mike-play-tip" v-if="isRecording">录音中...</view>
  25. <view class="mike-play-tip" v-else>长按 读一读</view>
  26. <!-- <view class="status">{{ recordingStatus }}</view> -->
  27. <!-- <view class="duration" v-if="isRecording">录音时长: {{ Math.floor(duration) }}秒</view> -->
  28. <view class="du-btn-box">
  29. <button class="play-btn" :class="{ 'playing-btn': isPlaying}" @click="playVoice"
  30. v-if="voicePath"></button>
  31. <button class="mike-btn" :class="{ 'mike-az-btn': isRecording}" @touchstart="handleTouchStart"
  32. @touchend="handleTouchEnd" @touchcancel="handleTouchEnd" :disabled="isPlaying">
  33. <!--{{ isRecording ? '松开结束' : '按住录音' }}
  34. <view v-if="isPlaying" class="disabled-mask">播放中不可录音</view> -->
  35. </button>
  36. </view>
  37. <!-- <button class="play-btn" :class="{ disabled: isRecording || !voicePath }" @click="playVoice"
  38. :disabled="isRecording || !voicePath">
  39. {{ isPlaying ? '播放中...' : '播放录音' }}
  40. <view v-if="isRecording" class="disabled-mask">录音中不可播放</view>
  41. </button> -->
  42. </view>
  43. </view>
  44. </view>
  45. <uni-popup ref="statusPopup" :animation="false" :is-mask-click="false"
  46. mask-background-color="rgba(51, 137, 217, 0.95);">
  47. <view class="ezy-image-dialog luyin">
  48. </view>
  49. </uni-popup>
  50. </template>
  51. <script setup>
  52. import selectTypesVue from './selectTypes.vue';
  53. import audioTwoVue from './audioTwo.vue';
  54. import yinbiaoTxtVue from "./yinbiaoTxt.vue"
  55. import {
  56. onLoad
  57. } from "@dcloudio/uni-app"
  58. import {
  59. reactive,
  60. ref,
  61. onMounted,
  62. onUnmounted
  63. } from 'vue';
  64. const props = defineProps({
  65. activeWord: {
  66. type: Object,
  67. },
  68. pageData: {
  69. type: Object,
  70. },
  71. activeWords: {
  72. type: Array
  73. },
  74. })
  75. const emits = defineEmits(['play-audio'])
  76. let tabFlag = ref(1)
  77. const audioInfo = ref(null)
  78. const data = reactive({
  79. name: '',
  80. yinbiao: '',
  81. jianyi: []
  82. })
  83. // 录音相关状态
  84. const isRecording = ref(false)
  85. const isPlaying = ref(false)
  86. const voicePath = ref('')
  87. const duration = ref(0)
  88. const timer = ref(null)
  89. const recordingStatus = ref('准备就绪')
  90. const startTime = ref(0)
  91. const longPressTimer = ref(null) // 长按计时器
  92. const isRecorderReady = ref(true) // 新增:录音器就绪状态
  93. // 获取录音和音频播放管理器
  94. const recorderManager = uni.getRecorderManager()
  95. const innerAudioContext = uni.createInnerAudioContext()
  96. const statusPopup = ref(null)
  97. const popupImage = ref('')
  98. const statusAudio = uni.createInnerAudioContext()
  99. // 初始化录音器
  100. const initRecorder = () => {
  101. recorderManager.onStart(() => {
  102. console.log('recorder start')
  103. isRecording.value = true
  104. isRecorderReady.value = true // 录音结束后标记为就绪
  105. // recordingStatus.value = '录音中...'
  106. // startTime.value = Date.now()
  107. // startTimer()
  108. })
  109. recorderManager.onStop((res) => {
  110. // const recordTime = (Date.now() - startTime.value) / 1000 // 计算实际录音时间
  111. isRecording.value = false
  112. isRecorderReady.value = true // 录音结束后标记为就绪
  113. // if (recordTime < 3) {
  114. // uni.showToast({
  115. // title: '录音时间太短,需3秒以上',
  116. // icon: 'none'
  117. // })
  118. // return
  119. // }
  120. if (res.tempFilePath) {
  121. voicePath.value = res.tempFilePath
  122. uni.showToast({
  123. title: '录音成功',
  124. icon: 'success'
  125. })
  126. showStatusPopup('', '录音成功!', '/static/mp3/newYingyu/right-tip.mp3')
  127. } else {
  128. uni.showToast({
  129. title: '录音失败',
  130. icon: 'none'
  131. })
  132. }
  133. })
  134. recorderManager.onError((res) => {
  135. console.error('recorder error', res)
  136. //stopTimer()
  137. isRecording.value = false
  138. isRecorderReady.value = true // 出错时也标记为就绪
  139. setTimeout(() => {
  140. initRecorder()
  141. }, 300)
  142. //recordingStatus.value = `录音错误: ${res.errMsg}`
  143. // uni.showToast({
  144. // title: `录音出错: ${res.errMsg}`,
  145. // icon: 'none'
  146. // })
  147. })
  148. innerAudioContext.onPlay(() => {
  149. isPlaying.value = true
  150. //recordingStatus.value = '播放中...'
  151. })
  152. innerAudioContext.onEnded(() => {
  153. isPlaying.value = false
  154. //recordingStatus.value = '播放完成'
  155. })
  156. innerAudioContext.onError((res) => {
  157. isPlaying.value = false
  158. console.error('play error', res)
  159. uni.showToast({
  160. title: '播放失败',
  161. icon: 'none'
  162. })
  163. })
  164. }
  165. const showStatusPopup = (imagePath, text, audioPath) => {
  166. console.log('audioPath', audioPath);
  167. // 播放音效
  168. statusAudio.stop()
  169. statusAudio.src = audioPath
  170. statusAudio.play()
  171. // 显示弹窗
  172. statusPopup.value.open()
  173. }
  174. const checkMicrophonePermission = async () => {
  175. try {
  176. // 1. 检查平台
  177. const {
  178. platform
  179. } = uni.getSystemInfoSync()
  180. // 2. Android权限处理
  181. if (platform === 'android') {
  182. console.log('1111');
  183. const status = await new Promise(resolve => {
  184. plus.android.requestPermissions(
  185. ['android.permission.RECORD_AUDIO'],
  186. (result) => {
  187. console.log('22222', result);
  188. if (result.deniedAlways?.length) {
  189. resolve(false) // 永久拒绝
  190. } else if (result.denied?.length) {
  191. resolve(false) // 拒绝
  192. } else {
  193. resolve(true) // 已授权
  194. }
  195. },
  196. () => resolve(false) // 出错
  197. )
  198. })
  199. console.log('status', status);
  200. if (!status) {
  201. uni.showToast({
  202. title: '需要麦克风权限',
  203. icon: 'none'
  204. })
  205. return false
  206. }
  207. }
  208. // 3. iOS权限处理
  209. else if (platform === 'ios') {
  210. const granted = await new Promise(resolve => {
  211. plus.ios.import('AVAudioSession').then(AVAudioSession => {
  212. const session = plus.ios.invoke(AVAudioSession, 'sharedInstance')
  213. plus.ios.invoke(session, 'requestRecordPermission:', resolve)
  214. plus.ios.deleteObject(session)
  215. }).catch(() => resolve(false))
  216. })
  217. if (!granted) {
  218. uni.showToast({
  219. title: '请在设置中允许麦克风权限',
  220. icon: 'none'
  221. })
  222. return false
  223. }
  224. }
  225. return true
  226. } catch (error) {
  227. console.error('权限检查错误:', error)
  228. return false
  229. }
  230. }
  231. async function handlePlay(opt) {
  232. emits('play-audio', opt)
  233. }
  234. // 处理触摸开始(移动端)
  235. const handleTouchStart = async(e) => {
  236. e.preventDefault()
  237. if (isPlaying.value) return
  238. // 先检查权限
  239. const hasPermission = await checkMicrophonePermission()
  240. if (!hasPermission) {
  241. return
  242. }
  243. // 设置长按计时器,500ms后才开始录音
  244. longPressTimer.value = setTimeout(() => {
  245. startRecording()
  246. }, 400)
  247. }
  248. // 处理触摸结束(移动端)
  249. const handleTouchEnd = (e) => {
  250. e.preventDefault()
  251. clearTimeout(longPressTimer.value)
  252. if (isRecording.value) {
  253. endRecording()
  254. }
  255. }
  256. // 处理触摸取消(移动端,如被系统中断)
  257. const handleTouchCancel = (e) => {
  258. handleTouchEnd(e) // 与touchend同样处理
  259. }
  260. // 开始录音
  261. const startRecording = async () => {
  262. if (isRecording.value || !isRecorderReady.value) return
  263. const hasPermission = await checkMicrophonePermission()
  264. if (!hasPermission) {
  265. // 权限被拒绝后重置状态
  266. isRecording.value = false
  267. isRecorderReady.value = true
  268. return
  269. }
  270. console.log('开始录音')
  271. //recordingStatus.value = '准备录音...'
  272. isRecording.value = true // 提前设置状态,避免延迟
  273. isRecorderReady.value = false
  274. // startTime.value = Date.now()
  275. // startTimer()
  276. const options = {
  277. duration: 60000,
  278. sampleRate: 44100,
  279. numberOfChannels: 1,
  280. encodeBitRate: 192000,
  281. format: 'mp3',
  282. frameSize: 50
  283. }
  284. try {
  285. await recorderManager.start(options)
  286. } catch (e) {
  287. console.error('启动录音失败:', e)
  288. isRecording.value = false
  289. isRecorderReady.value = true
  290. uni.showToast({
  291. title: '启动录音失败,请重试',
  292. icon: 'none'
  293. })
  294. }
  295. }
  296. // 结束录音
  297. const endRecording = () => {
  298. if (!isRecording.value) return
  299. console.log('停止录音')
  300. try {
  301. recorderManager.stop()
  302. } catch (e) {
  303. console.error('停止录音失败:', e)
  304. isRecording.value = false
  305. isRecorderReady.value = true
  306. }
  307. }
  308. const getRecordingDuration = () => {
  309. if (!isRecording.value) return 0
  310. return Math.floor((Date.now() - startTime.value) / 1000)
  311. }
  312. // 播放录音
  313. const playVoice = () => {
  314. if (isRecording.value || !voicePath.value) return
  315. console.log('播放录音:', voicePath.value)
  316. innerAudioContext.src = voicePath.value
  317. innerAudioContext.play()
  318. }
  319. // // 计时器相关
  320. // const startTimer = () => {
  321. // duration.value = 0
  322. // const start = Date.now()
  323. // timer.value = setInterval(() => {
  324. // // 计算实际经过的时间(毫秒),然后转换为秒
  325. // const elapsed = Math.floor((Date.now() - start) / 1000)
  326. // duration.value = elapsed
  327. // }, 200) // 缩短检查间隔,但计算基于实际时间差
  328. // }
  329. // const stopTimer = () => {
  330. // if (timer.value) {
  331. // clearInterval(timer.value)
  332. // timer.value = null
  333. // }
  334. // duration.value = 0
  335. // }
  336. // 初始化单词数据
  337. const initItem = () => {
  338. data.name = props.activeWord.name;
  339. data.yinbiao = props.activeWord.yinbiao;
  340. data.jianyi = props.activeWord.jianyi;
  341. console.log('data', data);
  342. }
  343. onMounted(() => {
  344. initItem()
  345. initRecorder()
  346. statusAudio.autoplay = false
  347. statusAudio.onEnded(() => {
  348. statusPopup.value.close()
  349. })
  350. })
  351. onUnmounted(() => {
  352. //stopTimer()
  353. clearTimeout(longPressTimer.value)
  354. try {
  355. recorderManager.stop()
  356. innerAudioContext.stop()
  357. innerAudioContext.destroy()
  358. statusAudio.destroy()
  359. } catch (e) {
  360. console.error('清理资源时出错:', e)
  361. }
  362. })
  363. </script>