Skip to content

多媒体功能

小程序的多媒体能力覆盖图片、视频、录音、音频、实时通话和直播。这篇按"选、拍、录、播、实时"五类讲,重点是权限、格式限制和工程封装。

一、图片:选择与压缩

js
wx.chooseMedia({
  count: 9,
  mediaType: ['image'],
  sourceType: ['album', 'camera'],
  sizeType: ['compressed'],        // original 原图,compressed 压缩
  success: (res) => {
    // res.tempFiles: [{ tempFilePath, size, width, height }]
    this.uploadImages(res.tempFiles);
  }
});

旧接口 wx.chooseImage 已不推荐,统一用 chooseMedia。上传前的客户端压缩:sizeType: ['compressed'] 只是系统级压缩,进一步压缩用 canvas:

js
function compressImage(path, maxW = 1080, quality = 0.8) {
  return new Promise((resolve) => {
    wx.getImageInfo({
      src: path,
      success: (info) => {
        const ratio = Math.min(maxW / info.width, 1);
        const canvas = wx.createOffscreenCanvas({ type: '2d', width: info.width * ratio, height: info.height * ratio });
        const ctx = canvas.getContext('2d');
        const img = canvas.createImage();
        img.onload = () => {
          ctx.drawImage(img, 0, 0, info.width * ratio, info.height * ratio);
          wx.canvasToTempFilePath({
            canvas,
            fileType: 'jpg',
            quality,
            success: (r) => resolve(r.tempFilePath)
          });
        };
        img.src = path;
      }
    });
  });
}

wx.canvasToTempFilePath 配合 offscreen canvas(2d)是新推荐方式,比旧 canvas-id 方式干净。压缩后 3-5MB 的原图通常能降到 200-500KB,上传成功率和速度完全两个世界。

相册保存:wx.saveImageToPhotosAlbum,需要 scope.writePhotosAlbum 授权。保存失败的常见原因是权限被拒,openSetting 引导。

二、相机拍照

两种模式:系统相机(chooseMedia 的 sourceType: ['camera'])和自定义相机(camera 组件)。

自定义相机的完整骨架:

xml
<camera
  device-position="{{devicePosition}}"
  flash="off"
  resolution="medium"
  frame-size="medium"
  binderror="onCameraError"
  style="width: 100%; height: 60vh;"
></camera>

<button bindtap="takePhoto">拍照</button>
<button bindtap="switchCamera">切换前后</button>
js
Page({
  data: { devicePosition: 'back' },

  takePhoto() {
    const ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        // res.tempImagePath 临时文件
        this.processPhoto(res.tempImagePath);
      },
      fail: (err) => console.error(err)
    });
  },

  switchCamera() {
    this.setData({ devicePosition: this.data.devicePosition === 'back' ? 'front' : 'back' });
  }
})

自定义相机的坑:

  • wx.createCameraContext() 在页面 onReady 后才能拿到实例
  • 权限:scope.camera,拒绝后只能引导去设置,没有降级(除非退回系统相机)
  • 全屏相机要处理状态栏和刘海:用 custom 导航栏 + 安全区 inset
  • 拍照后预览页自己写(全屏图 + 重拍/确认),别依赖系统行为

三、录音与音频

3.1 录音

js
const recorder = wx.getRecorderManager();

recorder.onStart(() => console.log('录音开始'));
recorder.onStop((res) => {
  // res.tempFilePath / res.duration / res.fileSize
  this.uploadAudio(res.tempFilePath);
});
recorder.onError((err) => console.error(err));

// 开始(可传 duration/format/sampleRate/numberOfChannels)
recorder.start({ duration: 60000, format: 'mp3' });

// 暂停/继续(部分版本支持)
recorder.pause();
recorder.resume();

recorder.stop();

录音要处理:录音中锁屏/来电中断(onInterruptionBegin/End 回调)、时长上限提示、权限(scope.record)。产品上必须有"松手结束、上滑取消"的手势,参考微信语音交互。

3.2 音频播放

背景音频(音乐、长音频,退后台继续播):

js
const bgAudio = wx.getBackgroundAudioManager();
bgAudio.title = '课程音频';
bgAudio.epname = '第 3 讲';
bgAudio.singer = '讲师';
bgAudio.coverImgUrl = 'https://cdn.example.com/cover.jpg';
bgAudio.src = 'https://cdn.example.com/audio.mp3';

bgAudio.onPlay(() => {});
bgAudio.onTimeUpdate(({ currentTime, duration }) => this.setData({ currentTime }));
bgAudio.onEnded(() => {});
bgAudio.onError((err) => {});

短音频(音效、提示音,不能退后台):

js
const innerAudio = wx.createInnerAudioContext();
innerAudio.src = '/assets/notice.mp3';
innerAudio.obeyMuteSwitch = false;   // 静音开关是否遵循
innerAudio.play();

选择标准:超过 30 秒、需要锁屏控制、退后台播放 → BackgroundAudioManager;短音效 → InnerAudioContext。iOS 上 innerAudio 受静音开关控制,obeyMuteSwitch = false 可强制外放。

音频体验细节:播放态全局唯一(切页面不重复播)、进度条可拖、耳机拔掉自动暂停(onStop 监听 system 事件)、息屏后定时器不准用音频时间轴驱动。

四、视频

video 组件是主力:

xml
<video
  src="{{videoUrl}}"
  poster="{{coverUrl}}"
  object-fit="cover"
  controls
  autoplay="{{false}}"
  loop="{{false}}"
  muted="{{false}}"
  show-mute-btn
  enable-play-gesture
  bindfullscreenchange="onFullScreen"
  bindtimeupdate="onTimeUpdate"
  style="width: 100%; height: 225px;"
/>

工程要点:

  • 首帧图用 poster,避免黑屏等待
  • 自动播放必须 muted,否则 iOS 不给你播
  • enable-play-gesture 显示中央播放按钮,引导点击
  • 全屏管理:bindfullscreenchange 里同步页面状态;全屏时自定义控制栏接管
  • 视频源走 CDN,mp4/H.264 兼容性最好;hls(m3u8)支持但低端机可能卡
  • 列表里多个 video 组件性能差:进入视口才 play(IntersectionObserver),离开 pause

五、实时音视频(RTC)

1v1 客服、语聊房、视频会议用 RTC。微信提供 TRTC 方案(腾讯实时音视频 SDK 的小程序版),也有声网等第三方:

js
// TRTC 小程序 SDK 典型初始化
const TRTC = require('trtc-wx-sdk');
const client = TRTC.createClient({ mode: 'rtc', sdkAppId, userId, userSig });

await client.join({ roomId });

// 推流(本地摄像头)
const localStream = TRTC.createStream({ userId, audio: true, video: true });
await localStream.initialize();
client.publish(localStream);

// 拉流(远端)
client.on('stream-added', async (e) => {
  await client.subscribe(e.stream);
});

关键概念:roomId 是房间,同一 room 的人互通;userSig 是服务端用 SDKSecretKey 签的票据(有有效期,过期要重新签);推拉流必须 HTTPS/WSS 环境。纯音频场景关 video 省电省流量。RTC 的计费按分钟,产品上要有"断开自动退房"逻辑,防止挂机烧钱。

六、直播

两种:小程序 live-player(企业主体 + 类目资质,播放腾讯云/阿里云直播流)和视频号直播(channel-live 组件,2022 后微信主推,无需自建)。新项目优先视频号直播组件,成本和合规压力都小得多。

xml
<channel-live
  feed-id="{{feedId}}"
  finder-user-name="{{finderUserName}}"
  bind:roomenter="onRoomEnter"
/>

需要视频号授权绑定,能力在开放平台申请。

七、常见问题

Q:chooseMedia 选图很慢? 相册上千张时系统组件加载慢,属系统行为;可引导用户"拍照"替代。别在页面上同时开多个选择器。

Q:录音文件播放失败? format 用 'mp3' 兼容性最好;检查文件是否上传后直接播服务端 URL(本地临时文件有时效,要及时转存)。

Q:video 在 iOS 上不全屏? iOS 限制 video 不能同层渲染在全屏之下,bindfullscreenchange 里接管控制栏;页面内嵌视频保持非全屏模式展示。

相关阅读

CTO Plus技术栈 Version 1.0.20261024-12