小程序uniapp播放录音,uni.createInnerAudioContext()苹果手机播放报错,安卓手机可以正常播放问题解决

解决思路:经过测试发现虽然苹果手机uni.createInnerAudioContext() api播放不了,会进入错误监听里面。但是uni.getBackgroundAudioManager()背景音乐播放在苹果手机上播放是正常的。所以我们采取能正常录音播放的就用uni.createInnerAudioContext()音频播放组件,如果播放进入createInnerAudioContext的错误监听事件,就使用uni.getBackgroundAudioManager()背景音乐播放组件。(因为苹果手机使用uni.createInnerAudioContext()是一进入页面就会报错,甚至还没点。所以一进入页面我们就可以知道是用createInnerAudioContext还是getBackgroundAudioManager)

以下是封装的组件:

<template>
  <!-- 音频播放器组件 -->
  <view v-if='url'
        class='flex justify-between align-center audio'>
    <view class='mr-3'
          @click='start(audioId)'>
      <image src='@/static/daily-supervision/play.png'
             class='icon'
             v-show='!status'></image>
      <image src='@/static/daily-supervision/pause.png'
             class='icon'
             v-show='status'></image>
    </view>
    <view class='flex-1'>
      <slider @change='changeAudio'
              :activeColor='activeColor'
              :min='0'
              :max='duration ? duration.toFixed(0) : "00:00"'
              :value='currentTime.toFixed(0)'
              :step='0.1'></slider>
    </view>
    <!-- <view class='ml-3'>{{getTime(Math.round(currentTime))}}</view> -->
    <view class='ml-3'>{{getTime(Math.round(totalDuration))}}</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      context: null,
      currentTime: 0,
      duration: 100,
      status: false,
      totalDuration: 0,
      bgAudioManager: null,
      useBackgroundAudioManager: false,
      flag: true
    };
  },
  props: {
    url: String,
    activeColor: {
      type: String,
      default: '#0E7EFC'
    },
    // startPic: String,
    // endPic: String,
    audioId: [String,Number]
  },
  created() {
    this.bgAudioManager = uni.getBackgroundAudioManager();
    this.context = uni.createInnerAudioContext();
    this.context.src = this.url;
    // uni.createInnerAudioContext事件听
    this.onTimeUpdate();
    this.onCanplay();
    this.onEnded();
    this.onErrorHandle();

    // uni.getBackgroundAudioManager事件监听
    this.onBgCanplay();
    this.onBgTimeUpdate();
    this.onBgEnded();
    this.onBgStop();

    uni.$on('stop',(id)=> {
      if(id && id != this.audioId) {
        this.context.stop();
        this.status = false;
      } else if(!id){
        this.context.stop();
        this.status = false;
      }
    });

    uni.$on('BackgroundAudioStop',(id)=> {
      if(id && id != this.audioId) {
        this.bgAudioManager.stop();
        this.status = false;
      } else if(!id){
        this.bgAudioManager.stop();
        this.status = false;
      }
    });

    uni.setInnerAudioOption({  
      obeyMuteSwitch: false  
    });
  },
  methods: {
    /**
     * uni.getBackgroundAudioManager事件监听
     */
    onBgCanplay() {
      this.bgAudioManager.onCanplay(() => {
        setTimeout(()=>{
          this.duration = this.bgAudioManager.duration;
          this.totalDuration = this.bgAudioManager.duration;
          console.log(this.duration, this.totalDuration);
        },1000);
      });
    },
    onBgTimeUpdate() {
      console.log('onBgTimeUpdate');
      this.bgAudioManager.onTimeUpdate(() => {
        console.log('onTimeUpdate');
        if (!Number.isFinite(this.bgAudioManager.duration)) {
          this.duration = this.bgAudioManager.currentTime + 10;
          this.currentTime = this.bgAudioManager.currentTime;
        } else {
          this.duration = this.bgAudioManager.duration;
          this.currentTime = this.bgAudioManager.currentTime;
        }
      });
    },
    onBgEnded() {
      this.bgAudioManager.onEnded(() => {
        this.status = false;
        this.currentTime = 0;
        this.flag = true;
        console.log('onBgEnded');
      });
    },
    onBgStop() {
      this.bgAudioManager.onStop(() => {
        this.status = false;
        this.currentTime = 0;
        this.flag = true;
        console.log('onBgStop');
      });
    },
    /**
     * uni.createInnerAudioContext事件听
     */
    start(id) { //点击播放
      let audioId = id;
      if (this.useBackgroundAudioManager) {
        console.log(this.bgAudioManager.src);
        if (this.flag) {
          this.bgAudioManager.src = this.url;
          this.flag = false;
        }
        this.duration = this.bgAudioManager.duration;
        console.log(21222, this.duration);
        if(this.status) {
          this.bgAudioManager.pause();
          this.status = !this.status;
        }else {
          // uni.$emit('BackgroundAudioStop',id);
          this.bgAudioManager.play();
          this.status = !this.status;
        }
        return;
      }
      if(this.status) {
        this.context.pause();
        this.status = !this.status;
      }else {
        uni.$emit('stop',id);
        this.context.play();
        this.status = !this.status;
      }
    },
    onCanplay() { //进入可播放状态
      this.context.onCanplay(() => {
        this.context.duration;
        setTimeout(()=>{
          this.duration = this.context.duration;
          this.totalDuration = this.context.duration;
        },1000);
      });
    },
    onTimeUpdate() { //音频播放进度
      this.context.onTimeUpdate(() => {
        console.log('onTimeUpdate');
        if (!Number.isFinite(this.context.duration)) {
          this.duration = this.context.currentTime + 10;
          this.currentTime = this.context.currentTime;
        } else {
          this.duration = this.context.duration;
          this.currentTime = this.context.currentTime;
        }
      });
    },
    onEnded() { //播放结束
      this.context.onEnded(()=> {
        this.status = false;
        this.currentTime = 0;
      });
    },
    onErrorHandle() {
      this.context.onError((res) => {
        console.log(res.errMsg);
        console.log(res.errCode);
        this.useBackgroundAudioManager = true;
        this.bgAudioManager.title = '报告回听';
        console.log('bgAudioManager.duration', this.bgAudioManager.duration);
      });
    },
    changeAudio(e) {
      // let paused = this.context.paused;
      // this.context.pause();
      // this.context.seek(e.detail.value);
      // if(!paused) {
      //   this.context.play();
      // } 
    },
    getTime(time) {
      let m = parseInt(time / 60);
      let s = time % 60;
      return this.towNum(m) + ':' + this.towNum(s);
    },
    towNum(num) {
      if(num >= 10) {
        return num;
      }else {
        return '0' + num;
      }
    }
  }
};
</script>

<style>
.audio {
  background: #f4f4f4;
  padding: 20rpx;
}

.icon {
  width: 60rpx;
  height: 60rpx;
}

.flex {
  display: flex;
  flex-direction: row;
}

.justify-between {
  justify-content: between;
}

.align-center {
  align-items: center;
}

.flex-1 {
  flex: 1;
}

.ml-3 {
  margin-left: 30rpx;
}

.mr-3 {
  margin-right: 30rpx;
}
</style>

使用

          <UniAudio :audioId='item.id'
                    :url="audioUrl"></UniAudio>
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在uni-app中使用uni.downloadFile下载文件时,可能会遇到跨域问题。为了解决这个问题,我们需要采取以下步骤: 1. 在`manifest.json`文件中的`uni.downloadFile`节点下的`service`字段中添加合法的域名列表。例如,如果要下载的文件来自不同的域名,我们需要将这些域名添加到`service`字段中。 2. 在服务器端配置合适的跨域策略。这可以通过在服务器的响应头中添加`Access-Control-Allow-Origin`字段来实现。将其设置为允许访问的域名,以解决跨域访问的问题。 3. 如果下载的文件不是来自同一域名,那么还需要进行代理跨域。我们可以通过在服务器上设置代理来实现这一点。具体的设置方法可以参考uni-app官方文档中关于代理跨域的部分。 总结而言,解决uni-app中使用uni.downloadFile下载文件时的跨域问题需要在manifest.json中配置合法域名列表,并在服务器端进行相关的跨域配置,以确保下载请求能够正常进行。 ### 回答2: 在uniapp中使用uni.downloadFile下载文件时出现跨域问题可以通过以下几种方式解决: 1. 配置服务器端允许跨域访问:在服务端配置响应头信息,添加允许跨域访问的相关参数,比如设置Access-Control-Allow-Origin为"*",表示允许所有域进行访问。这样就可以解决跨域访问的问题。 2. 使用代理:可以在uniapp的配置文件(如vue.config.js)中配置代理,将请求发送到与服务器同域的地址上,避免跨域问题。例如,可以设置代理 "/api" 到实际后端地址,这样在请求时就可以先访问代理,再由代理转发到实际后端地址。 3. 使用uni.request代替uni.downloadFile:uni.request函数不受跨域限制,可以用于下载文件,只需要将responseType设置为"arraybuffer"或"file",然后使用uni.saveFile保存文件。 除了以上的解决方法,还可以使用其他插件或工具,如HbuilderX里的EasyMock工具,来模拟请求和响应,帮助解决跨域问题。总之,根据实际情况选择合适的解决方案来解决uniapp中使用uni.downloadFile下载文件时出现的跨域问题。 ### 回答3: 在uniapp中,使用uni.downloadFile下载文件时出现跨域问题,我们可以通过以下步骤解决: 1. 配置后端服务器:在服务器端设置响应头部,允许来自不同域的请求。可以在后端代码中添加如下代码: ```python response.setHeader("Access-Control-Allow-Origin", "*"); ``` 2. 配置uniapp前端:在uniapp的请求中添加header,使得请求带上cookie。可以在请求代码中添加如下代码: ```javascript uni.downloadFile({ url: 'yoururl', header: { 'content-type': 'application/json', 'cookie': 'yourcookie' }, success: function (res) { if (res.statusCode === 200) { console.log('下载成功'); } } }) ``` 其中,'yoururl'是下载文件的URL地址,'yourcookie'是根据后端返回的cookie设置的。 3. 配置uniapp的配置文件:在uniapp的配置文件manifest.json中,添加需要跨域的服务器地址到"networkTimeout"中的"request"字段,如下所示: ```json "networkTimeout": { "request": 20000, "downloadFile": 60000, "uploadFile": 60000, "socketTask": 60000, "file": 60000 }, "debug": { "networkTimeout": { "request": 20000, "downloadFile": 60000, "uploadFile": 60000, "socketTask": 60000, "file": 60000 } }, "app-plus": { "HTTP_SERVER_URL": { "request": { "domainList": ["yourdomain"] //添加需要跨域的服务器地址 } } } ``` 在以上示例中,'yourdomain'是需要跨域的服务器地址。 通过以上步骤,我们可以解决uniapp中使用uni.downloadFile下载文件时出现的跨域问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值