微信小程序学习之路——API媒体

媒体

图片

wx.chooseImage(Object)

从本地相册选择图片或者使用相机拍照,拍照时产生的临时路径小程序本次启动期间都可以正常使用,如果需要持久保存,就要主动调用wx.saveFile,这样才能保证小程序下次启动时访问到,Object参数属性如下:

属性 类型 默认值 必填 说明
count number 9 最多可以选择的图片张数
sizeType Array.<string> ['original', 'compressed'] 所选的图片的尺寸
sourceType Array.<string> ['album', 'camera'] 选择图片的来源
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

<view>
  <image src='{{src}}'></image>
  <button bindtap='chooseImage'>选择图片</button>
</view>
Page({
  src:'',
  chooseImage:function(){
    var self = this;
    wx.chooseImage({
      count:1,
      sizeType:['original','compressed'],
      sourceType:['album','camera'],
      success:function(res){
        console.log(res.tempFilePaths);
      }
    });
  }
});

wx.previewImage(Object)

预览图片,调用后小程序会开启图片浏览界面,Object参数属性如下:

属性 类型 默认值 必填 说明
urls Array.<string>   需要预览的图片链接列表。2.2.3 起支持云文件ID。
current string urls 的第一张 当前显示图片的链接
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)
wx.previewImage({//默认先显示第二张
  current:'3.jpg',
  urls: ['2.jpg',
  '3.jpg'
  ],
});

wx.getImageInfo()

获取图片信息,Object属性如下:

属性 类型 默认值 必填 说明
src string   图片的路径,可以是相对路径、临时文件路径、存储文件路径、网络图片路径
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

chooseImage:function(){
  wx.chooseImage({
    success: function(res) {
      wx.getImageInfo({
        src: 'res.tempFilePaths[0]',
        success:function(info){
          console.log(info);
        }
      });
    },
  })
}

录音

wx.startRecord(Object)

开始录音。当主动调用wx.stopRecord,或者录音超过1分钟时自动结束录音,但会录音文件的临时文件路径用户离开小程序时,此接口无法调用。录音接口需要用户授权,业务代码中需要考虑用户拒绝授权的场景。Obeject参数属性:

属性 类型 默认值 必填 说明
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

wx.startRecord({
  success:function(res){
    var tempFilePath = res.tempFilePath
    wx.playVoice({//录音完成后立即播放
      filePath: 'tempFilePath',
    })
  }
})

wx.stopRecord()

主动调用停止录音

根据上例代码,本例在10秒钟后停止录音,示例代码如下:

wx.startRecord({
  success:function(res){
    var tempFilePath = res.tempFilePath
    wx.playVoice({
      filePath: 'tempFilePath',
    });
  }
});
setTimeout(function(){
  wx.stopRecord();
},10000);

音频播放控制

wx.playVoice(Object)

开始播放语音时只允许一个语音文件播放,如果前一个语音文件还没有播放完,将中断前一个语音播放后再进行播放下一个,Object参数属性如下:

属性 类型 默认值 必填 说明 最低版本
filePath string   需要播放的语音文件的文件路径  
duration number 60 指定录音时长,到达指定的录音时长后会自动停止录音,单位:秒 1.6.0
success function   接口调用成功的回调函数  
fail function   接口调用失败的回调函数  
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

wx.startRecord({
  success:function(res){
    var tempFilePath = res.tempFilePath
    wx.playVoice({//录音完成后立即播放
      filePath: 'tempFilePatj',
    });
  }
});

wx.pauseVoice()

暂停正在播放的语音,再次调用wx.playVoice播放同一个文件时,会从暂停处开始播放,如果想从头开始播放,需要先调用wx.stopVoice

根据上例代码,我们实现5秒后自动暂停播放,示例代码如下:

wx.startRecord({
  success:function(res){
    var tempFilePath =res.tempFilePath
    wx.playVoice({//录音完成后立即播放
      filePath: 'tempFilePath',
    });
    setTimeout(function(){
      wx.pauseVoice();
    },5000);
  }
});

wx.stopVoice()

结束播放语音,示例代码如下:

wx.startRecord({
  success:function(res){
    var tempFilePath =res.tempFilePath
    wx.playVoice({
      //录音完成后立即播放
      filePath:tempFilePath
    });
    setTimeout(function(){
      wx.stopVoice();
    },5000);
  }
});

音乐播放器控制

wx.getBackgroundAudioPlayerState(Object)

获取后台音乐播放状态,调用本方法时可以获取<audio/>组件或wx.playBackgroundAudio()方法播放音乐,Object参数属性如下:

属性 类型 默认值 必填 说明
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

wx.getBackgroundAudioPlayerState({
  success:function(res){
    var statusTest = {
      2:'没有音乐在播放',
      1:'播放中',
      0:'暂停中'
    }
    console.log(statusText[res.status]);
  }
});

wx.playBackgroundAudio(Object)

播放音乐,同时只能由一首音乐正在播放,Object参数属性如下:

属性 类型 默认值 必填 说明
dataUrl string   音乐链接,目前支持的格式有 m4a, aac, mp3, wav
title string   音乐标题
coverImgUrl string   封面URL
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

wx.playBackgroundAudio({
  dataUrl: '',
  title: '',
  coverImgUrl: '',
  success:function(){
    console.log('开始播放音乐了');
  }
});

wx.pauseBackgroundAudio()

暂停播放音乐

示例代码如下:

wx.playBackgroundAudio({
  dataUrl: '',
  title:'',
  coverImgUrl:'',
  success:function(){
    console.log('开始播放音乐了');
  }
});
setTimeout(function(){
  console.log('暂停播放');
  wx.pauseBackgroundAudio();
},6000);//60秒自动暂停

wx.seekBackgroundAudio(Object)

控制音乐播放进度,利用这个API可以实现音乐的快进、快退和播放位置拖动功能,Object属性如下:

属性 类型 默认值 必填 说明
position number   音乐位置,单位:秒
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)
wx.getBackgroundAudioPlayerState({
  success:function(res){
    var currentPosition =res.currentPosition;
    wx.seekBackgroundAudio({
      position: currentPosition+30,
    });
  }
});

wx.stopBackgroundAudio()

停止播放音乐

示例代码如下:

wx.playBackgroundAudio({
  dataUrl: '',
  title:'',
  coverImgUrl:'',
  success:function(){
    console.log('开始播放音乐了');
  }
});
setTimeout(function(){
  console.log('停止播放');
  wx.stopBackgroundAudio();
},60000);//60秒后自动停止

wx.onBackgroundAudioPlay(callback)

监听音乐播放

示例代码如下:

wx.onBackgroundAudioPlay(function(){
  console.log('音乐播放');
});
wx.playBackgroundAudio({
  dataUrl: '',
  title:'',
  coverImgUrl:'',
  success:function(){
    console.log('开始播放音乐了');
  }
});

wx.onBackgroundAudioPause(callback)

监听音乐暂停

示例代码如下:

wx.onBackgroundAudioPause(function(){
  console.log('音乐暂停');
});
wx.playBackgroundAudio({
  dataUrl: '',
  title:'',
  coverImgUrl:'',
  success:function(){
    console.log('开始播放音乐了');
  }
});

wx.onBackgroundAudioStop(callback)

监听音乐停止

示例代码如下:

wx.onBackgroundAudioStop(function(){
  console.log('音乐停止'');
});
wx.playBackgroundAudio({
  dataUrl:'',
  title:'',
  coverImgUrl:'',
  success:function(){
    console.log('开始播放音乐了');
  }
});

音频组件控制

wx.createAudioContext(audioId)创建并返回audio上下文audioContext对象,audioContext通过audio和一个<audio/>组件绑定,通过它可以操作对应的<audio/>组件,audioContext对象方法如下:

  • setSrc:设置音频地址
  • play:播放
  • pause:暂停
  • seek:跳转到指定位置,单位为s

利用播放相关API配合<audio/>我们可以创建自定义样式播放器,实例代码如下:

<audio
  poster='{{poster}}'
  name='{{name}}'
  author='{{author}}'
  src='{{src}}'
  id='myAudio'
  controls
  loop></audio>

  <button type='primary' bindtap='audioPlay'>播放</button>
  <button type='primary' bindtap='audioPause'>暂停</button>
  <button type='primary' bindtap='audio14'>设置当前播放时间为14秒</button>
  <button type='primary' bindtap='audioStart'>回到开头</button>
Page({
  onReady(e) {
    // 使用 wx.createAudioContext 获取 audio 上下文 context
    this.audioCtx = wx.createAudioContext('myAudio')
    this.audioCtx.setSrc('http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46')
    this.audioCtx.play()
  },
  data: {
    src: ''
  },
  audioPlay() {
    this.audioCtx.play()
  },
  audioPause() {
    this.audioCtx.pause()
  },
  audio14() {
    this.audioCtx.seek(14)
  },
  audioStart() {
    this.audioCtx.seek(0)
  }
})

执行结果如下:

视频:

wx.chooseVideo(Object)拍摄视频或从手机相册中选取视频,返回视频的临时文件,Object参数属性如下:

属性 类型 默认值 必填 说明 最低版本
sourceType Array.<string> ['album', 'camera'] 视频选择的来源  
compressed boolean true 是否压缩所选择的视频文件 1.6.0
maxDuration number 60 拍摄视频最长拍摄时间,单位秒  
camera string 'back' 默认拉起的是前置或者后置摄像头。部分 Android 手机下由于系统 ROM 不支持无法生效  
success function   接口调用成功的回调函数  
fail function   接口调用失败的回调函数  
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

  wx.chooseVideo({
    sourceType:['album','camera'],
    camera:['front','back'],
    success:function(res){
      console.log(res.tempFilePath);
    }
  });

视频组件控制

wx.createVideoContext(videoId)通用wx.createAudioContext(audioId)一样,wx.createVideoContext(videoId)用于创建并返回video上下文videoContext对象,video-Context对象方法如下:

  • play:播放
  • pause:暂停
  • seek:跳转到指定位置,单位s
  • sendDanmu:发送弹幕,danmu包含两个属性text,color

示例代码如下:

<view class="page-body">
  <view class='section tc'>
    <video id="myVideo" src="http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400" binderror="videoErrorCallback" danmu-list="{{danmuList}}" enable-danmu danmu-btn controls></video>
  <view class='cells'>
   <view class='label'>弹幕内容:</view>
   <input bindblur='bindInputBlur' class='input' type='text' placeholder='在此输入弹幕内容' ></input>
  </view>
   <view class='btn-area'>
    <button bindtap='bindButtonTap' class='page-body-button' type='primary'>获取视频</button>
    <button bindtap='bindSendDanmu' class='page-body-button' type='primary' form-type='submit'>发送弹幕</button>
    <button bindtap="bindPlay" class="page-body-button" type="primary">播放</button>
      <button bindtap="bindPause" class="page-body-button" type="primary">暂停</button>
    </view>
  </view>
</view>
function getRandomColor () {
  const rgb = []
  for (let i = 0 ; i < 3; ++i){
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length == 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}
Page({
  onReady(res){
    this.videoContext = wx.createVideoContext("myVideo")
  },
  inputValue:"",
  data:{
    src:"",
    danmuList:[
      {
        text:'第一秒出现的弹幕',
        color:getRandomColor(),
        time:1
      },
      {
        text: '第 3s 出现的弹幕',
        color: getRandomColor(),
        time: 3
        }]
  },
  bindInputBlur: function (e) {
    this.inputValue = e.detail.value
  },
  bindSendDanmu: function () {
    this.videoContext.sendDanmu({
      text: this.inputValue,
      color: getRandomColor()
    })
  },
  bindButtonTap(){
    const that =this
    wx.chooseVideo({
      sourceType:['album','camera'],
      maxDuration:60,
      camera:['front','back'],
      success(res){
        that.setData({
          src:res.tempFilePath
        })
      }
    })
  },

  bindPlay:function(){
    this.videoContext.play()
  },
  bindPause:function(){
    this.videoContext.pause()
  },
  videoErrorCallback:function(e){
    console.log('视频信息错误')
    console.log(e.detai.errMsg)
  }
 
})
.page-body-button {
  margin-bottom: 30rpx;
}
.label{  width: 5em;}

.input{ height: 2.58823529em;
  min-height: 2.58823529em;
  line-height: 2.58823529em;
  }

.cells{ margin-top: 80rpx;
  text-align: left;
  }
/**app.wxss**/
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 200rpx 0;
  box-sizing: border-box;
} 
.page-body {
  padding: 20rpx 0;
}
.tc{
  text-align: center;
}
.btn-area{
  margin-top: 60rpx;
  box-sizing: border-box;
  width: 100%;
  padding: 0 30rpx;
}
page {
  background-color: #F8F8F8;
  height: 100%;
  font-size: 32rpx;
  line-height: 1.6;
}

执行结果如下:

猜你喜欢

转载自blog.csdn.net/CSDN_XUWENHAO/article/details/89003796