readContent.vue 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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', 'luyinSuccess'])
  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. // 初始化录音器
  97. const initRecorder = () => {
  98. recorderManager.onStart(() => {
  99. console.log('recorder start')
  100. isRecording.value = true
  101. isRecorderReady.value = true // 录音结束后标记为就绪
  102. // recordingStatus.value = '录音中...'
  103. // startTime.value = Date.now()
  104. // startTimer()
  105. })
  106. recorderManager.onStop((res) => {
  107. // const recordTime = (Date.now() - startTime.value) / 1000 // 计算实际录音时间
  108. isRecording.value = false
  109. isRecorderReady.value = true // 录音结束后标记为就绪
  110. // if (recordTime < 3) {
  111. // uni.showToast({
  112. // title: '录音时间太短,需3秒以上',
  113. // icon: 'none'
  114. // })
  115. // return
  116. // }
  117. if (res.tempFilePath) {
  118. voicePath.value = res.tempFilePath
  119. uni.showToast({
  120. title: '录音成功',
  121. icon: 'success'
  122. })
  123. emits('luyinSuccess')
  124. //showStatusPopup('', '录音成功!', '/static/mp3/newYingyu/right-tip.mp3')
  125. } else {
  126. uni.showToast({
  127. title: '录音失败',
  128. icon: 'none'
  129. })
  130. }
  131. })
  132. recorderManager.onError((res) => {
  133. console.error('recorder error', res)
  134. //stopTimer()
  135. isRecording.value = false
  136. isRecorderReady.value = true // 出错时也标记为就绪
  137. setTimeout(() => {
  138. initRecorder()
  139. }, 300)
  140. //recordingStatus.value = `录音错误: ${res.errMsg}`
  141. // uni.showToast({
  142. // title: `录音出错: ${res.errMsg}`,
  143. // icon: 'none'
  144. // })
  145. })
  146. innerAudioContext.onPlay(() => {
  147. isPlaying.value = true
  148. //recordingStatus.value = '播放中...'
  149. })
  150. innerAudioContext.onEnded(() => {
  151. isPlaying.value = false
  152. //recordingStatus.value = '播放完成'
  153. })
  154. innerAudioContext.onError((res) => {
  155. isPlaying.value = false
  156. console.error('play error', res)
  157. uni.showToast({
  158. title: '播放失败',
  159. icon: 'none'
  160. })
  161. })
  162. }
  163. const checkMicrophonePermission = async () => {
  164. try {
  165. // 1. 检查平台
  166. const {
  167. platform
  168. } = uni.getSystemInfoSync()
  169. // 2. Android权限处理
  170. if (platform === 'android') {
  171. console.log('1111');
  172. const status = await new Promise(resolve => {
  173. plus.android.requestPermissions(
  174. ['android.permission.RECORD_AUDIO'],
  175. (result) => {
  176. console.log('22222', result);
  177. if (result.deniedAlways?.length) {
  178. resolve(false) // 永久拒绝
  179. } else if (result.denied?.length) {
  180. resolve(false) // 拒绝
  181. } else {
  182. resolve(true) // 已授权
  183. }
  184. },
  185. () => resolve(false) // 出错
  186. )
  187. })
  188. console.log('status', status);
  189. if (!status) {
  190. uni.showToast({
  191. title: '需要麦克风权限',
  192. icon: 'none'
  193. })
  194. return false
  195. }
  196. }
  197. // 3. iOS权限处理
  198. else if (platform === 'ios') {
  199. const granted = await new Promise(resolve => {
  200. plus.ios.import('AVAudioSession').then(AVAudioSession => {
  201. const session = plus.ios.invoke(AVAudioSession, 'sharedInstance')
  202. plus.ios.invoke(session, 'requestRecordPermission:', resolve)
  203. plus.ios.deleteObject(session)
  204. }).catch(() => resolve(false))
  205. })
  206. if (!granted) {
  207. uni.showToast({
  208. title: '请在设置中允许麦克风权限',
  209. icon: 'none'
  210. })
  211. return false
  212. }
  213. }
  214. return true
  215. } catch (error) {
  216. console.error('权限检查错误:', error)
  217. return false
  218. }
  219. }
  220. async function handlePlay(opt) {
  221. emits('play-audio', opt)
  222. }
  223. // 处理触摸开始(移动端)
  224. const handleTouchStart = async (e) => {
  225. e.preventDefault()
  226. if (isPlaying.value) return
  227. // 先检查权限
  228. const hasPermission = await checkMicrophonePermission()
  229. if (!hasPermission) {
  230. return
  231. }
  232. // 设置长按计时器,500ms后才开始录音
  233. longPressTimer.value = setTimeout(() => {
  234. startRecording()
  235. }, 400)
  236. }
  237. // 处理触摸结束(移动端)
  238. const handleTouchEnd = (e) => {
  239. e.preventDefault()
  240. clearTimeout(longPressTimer.value)
  241. if (isRecording.value) {
  242. endRecording()
  243. }
  244. }
  245. // 处理触摸取消(移动端,如被系统中断)
  246. const handleTouchCancel = (e) => {
  247. handleTouchEnd(e) // 与touchend同样处理
  248. }
  249. // 开始录音
  250. const startRecording = async () => {
  251. if (isRecording.value || !isRecorderReady.value) return
  252. const hasPermission = await checkMicrophonePermission()
  253. if (!hasPermission) {
  254. // 权限被拒绝后重置状态
  255. isRecording.value = false
  256. isRecorderReady.value = true
  257. return
  258. }
  259. console.log('开始录音')
  260. //recordingStatus.value = '准备录音...'
  261. isRecording.value = true // 提前设置状态,避免延迟
  262. isRecorderReady.value = false
  263. // startTime.value = Date.now()
  264. // startTimer()
  265. const options = {
  266. duration: 60000,
  267. sampleRate: 44100,
  268. numberOfChannels: 1,
  269. encodeBitRate: 192000,
  270. format: 'mp3',
  271. frameSize: 50
  272. }
  273. try {
  274. await recorderManager.start(options)
  275. } catch (e) {
  276. console.error('启动录音失败:', e)
  277. isRecording.value = false
  278. isRecorderReady.value = true
  279. uni.showToast({
  280. title: '启动录音失败,请重试',
  281. icon: 'none'
  282. })
  283. }
  284. }
  285. // 结束录音
  286. const endRecording = () => {
  287. if (!isRecording.value) return
  288. console.log('停止录音')
  289. try {
  290. recorderManager.stop()
  291. } catch (e) {
  292. console.error('停止录音失败:', e)
  293. isRecording.value = false
  294. isRecorderReady.value = true
  295. }
  296. }
  297. const getRecordingDuration = () => {
  298. if (!isRecording.value) return 0
  299. return Math.floor((Date.now() - startTime.value) / 1000)
  300. }
  301. // 播放录音
  302. const playVoice = () => {
  303. if (isRecording.value || !voicePath.value) return
  304. console.log('播放录音:', voicePath.value)
  305. innerAudioContext.src = voicePath.value
  306. innerAudioContext.play()
  307. }
  308. // // 计时器相关
  309. // const startTimer = () => {
  310. // duration.value = 0
  311. // const start = Date.now()
  312. // timer.value = setInterval(() => {
  313. // // 计算实际经过的时间(毫秒),然后转换为秒
  314. // const elapsed = Math.floor((Date.now() - start) / 1000)
  315. // duration.value = elapsed
  316. // }, 200) // 缩短检查间隔,但计算基于实际时间差
  317. // }
  318. // const stopTimer = () => {
  319. // if (timer.value) {
  320. // clearInterval(timer.value)
  321. // timer.value = null
  322. // }
  323. // duration.value = 0
  324. // }
  325. // 初始化单词数据
  326. const initItem = () => {
  327. data.name = props.activeWord.name;
  328. data.yinbiao = props.activeWord.yinbiao;
  329. data.jianyi = props.activeWord.jianyi;
  330. console.log('data', data);
  331. }
  332. onMounted(() => {
  333. initItem()
  334. initRecorder()
  335. })
  336. onUnmounted(() => {
  337. //stopTimer()
  338. clearTimeout(longPressTimer.value)
  339. try {
  340. recorderManager.stop()
  341. innerAudioContext.stop()
  342. innerAudioContext.destroy()
  343. statusAudio.destroy()
  344. } catch (e) {
  345. console.error('清理资源时出错:', e)
  346. }
  347. })
  348. </script>