vue项目,解决ios下audio无法播放问题

7 篇文章 0 订阅
7 篇文章 0 订阅

最近在做一个关于aduio的项目,奈何audio在pc端能正常播放,在ios端确无法播放,着实踩了不少的坑!!!
也看了不少的网上的教程,最后的实现结果如下:
在这里插入图片描述
1、html代码

// html
<audio id="audio" :src="src" ref="audio" @timeupdate="updateTime" >该浏览器不支持audio属性</audio>
<div v-if="isMobile">
  <div class="playbtn"  @touchstart="play" v-if="!isPlay"></div>
  <div class="stopbtn"  @touchstart="pause" v-else></div>
</div>
<div v-else>
  <div class="playbtn"  @click="play" v-if="!isPlay"></div>
  <div class="stopbtn"  @click="pause" v-else></div>
</div>

不支持audio元素的浏览器会显示标签内文字
(1)、视频/音频(audio/video)在加载过程中,触发的顺序如下:
onloadstart:事件在浏览器开始寻找指定视频/音频(audio/video)触发。
ondurationchange 事件在视频/音频(audio/video)的时长发生变化时触发。
注意: 当视频/音频(audio/video)已经加载后,视频/音频(audio/video)的时长从 “NaN” 修改为正在的时长。
onloadedmetadata 事件在指定视频/音频(audio/video)的元数据加载后触发。
视频/音频(audio/video)的元数据包含: 时长,尺寸大小(视频),文本轨道。
onloadeddata 事件在当前帧的数据加载完成且还没有足够的数据播放视频/音频(audio/video)的下一帧时触发。
onprogress 事件在浏览器下载指定的视频/音频(audio/video)时触发。
oncanplay 事件在用户可以开始播放视频/音频(audio/video)时触发。
oncanplaythrough 事件在视频/音频(audio/video)可以正常播放且无需停顿和缓冲时触发。
(2)、audio的属性
src:音频地址
autoplay:音频加载完毕后自动播放
controls:显示播放控制条
loop:播放完毕后会重复播放
preload:1)auto 预加载音频视频。2)metadata 只预加载音频视频元数据。 有autoplay时此属性无效。
(3)、js
play() 播放
pause() 暂停
load() 重新加载
(3)、微信端和手机不能支持自动播放问题
原因是:android ios 内部原因为了节省流量,规定不自动播放音频视频,ios系统下会自动屏蔽audio标签的自动播放,需要使用一个事件来驱动音频播放
audio.load()

2、js代码
手机端用touchstart事件来驱动,pc端用click驱动

export default {
  data () {
    return {
      duration: 0,  // 视频音频的总时长
      currentTime: 0, // 播放时间
      isPlay: false, // 是否播放
      width: 0 // 视频音频的总时间的长度条
    }
  },
  props: ['src', 'isMobile'],
  computed: {
   // 获取音频/视频的总时间
    durationText () {
      return this._parseTime(this.duration)
    },
    // 获取音频/视频的播放时间
    currentTimeText () {
      return this._parseTime(this.currentTime)
    },
    // 获取音频的播放滚动条的长度
    progressBarLength () {
      return this.currentTime / this.duration * this.width
    }
  },
  mounted () {
    this.width = parseInt(window.getComputedStyle(this.$refs.bar).getPropertyValue('width'))
    this.audio = this.$refs.audio
    // 获取视频音频总时长
    this.audio.ondurationchange = () => {
      this.duration = this.audio.duration
    }
  },
  methods: {
   // 获取视频/音频正在播放的时间
    updateTime () {
      this.currentTime = this.audio.currentTime
      if (this.audio.ended) {
        this.isPlay = false
      }
    },
    // 播放
    play () {
      this.audio.load()
      this.audio.play()
      this.isPlay = true
    },
    // 暂停
    pause () {
      this.audio.pause()
      this.isPlay = false
    },
    // 把获取的视频音频时长,转化成具体的时间格式
    _parseTime (sec) {
      let minutes = parseInt(sec / 60)
      let seconds = parseInt(sec - 60 * minutes)
      return (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds)
    }
  }
}
</script>

相关文章:
https://www.cnblogs.com/volare/p/6759835.html
https://segmentfault.com/q/1010000000390733
https://blog.csdn.net/SoySauce_lm/article/details/86476004
https://www.cnblogs.com/cpqwebfe/p/7543256.html
https://segmentfault.com/q/1010000012624104/a-1020000012624254
https://blog.csdn.net/cmyh100/article/details/80695271

在UniApp中,如果你想要在iOS平台上使用NativeJS获取音频的实时分贝值,你需要通过原生的AVFoundation框架来实现,因为这个功能不是JavaScript可以直接提供的。以下是简单的步骤: 1. 首先,确保在你的项目中启用了iOS原生插件支持。在`uni-app.config.js`文件中配置: ```javascript // uni-app.config.js export default { // ... platform: { // 其他平台配置... ios: { enableNative插件: true, }, }, }; ``` 2. 然后,在Native层创建一个Objective-C或Swift的模块,例如创建一个名为`AudioHelperPlugin`的Cocoa Touch Class(Objective-C)或Swift类,用于处理录音和分贝计算。 3. 在Objective-C中,可以使用以下代码片段来获取音频分贝: ```objective-c #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> @interface AudioHelperPlugin : NSObject <AVAudioRecorderDelegate> @property (nonatomic, strong) AVAudioRecorder *audioRecorder; + (void)getDdB:(CDVInvokedUrlCommand *)command; - (void)startRecordingWithCallback:(CDVInvokedUrlCommand *)command; @end @implementation AudioHelperPlugin // ...其他方法... - (void)startRecordingWithCallback:(CDVInvokedUrlCommand *)command { // 创建录音设置 NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init]; [recordSettings setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey]; [recordSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; // 采样率 [recordSettings setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey]; // 单声道 [recordSettings setValue:[NSNumber numberWithBool:YES] forKey:AVLinearPCMBitDepthKey]; // 初始化录音者 NSURL *audioURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:NO]; _audioRecorder = [[AVAudioRecorder alloc] initWithURL:audioURL settings:recordSettings error:nil]; _audioRecorder.delegate = self; _audioRecorder.meteringEnabled = YES; // 开启实时监控音量 // 开始录制 [_audioRecorder prepareToRecord]; [_audioRecorder record]; CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:@{@"callbackId": command.callbackId}]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } // ...添加停止录音、获取分贝等方法并实现AVAudioRecorderDelegate回调 @end ``` 在Swift中,类似地,你可以创建一个AudioHelperPlugin.swift文件,并按照Apple官方文档编写相关功能。 4. 在Vue组件中调用这个NativeJS模块,比如: ```vue <template> <!-- ... --> </template> <script> import { uniCloudCallJSMethod } from '@dcloudio/uni-cli-plugin-uniapp-native'; export default { methods: { async getAudioLevel() { try { const result = await uniCloudCallJSMethod({ name: 'AudioHelperPlugin.getDdB', params: {}, success(data) { console.log('Received dB:', data.dB); }, fail(error) { console.error('Error:', error); } }); } catch (e) { console.error('Error calling NativeJS:', e); } }, }, created() { this.startRecording(); }, beforeDestroy() { if (this.audioRecorder) { this.audioRecorder.stop(); } }, }; </script> ``` 5.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值