开发
API

InnerAudioContext.play

播放。

语法

InnerAudioContext.play()

参数说明

扫码体验

请使用字节宿主APP扫码

代码示例

开发者工具中预览

【代码示例 1】:播放网络音频文件

<!-- index.ttml -->
<button type="primary" bindtap="play">播放</button>
// index.js
let dataUrl = "https://sf1-ttcdn-tos.pstatp.com/obj/developer/sdk/0000-0001.mp3";

Page({
  onShow: function () {
    let iac = (this.innerAudioContext = tt.createInnerAudioContext());

    iac.src = dataUrl;
    iac.startTime = 0;
    iac.autoplay = false;
    iac.loop = false;
    iac.obeyMuteSwitch = false;

    iac.onCanplay(() => {
      console.log("onCanplay", "音频进入可以播放状态,但不保证后面可以流畅播放");
    });

    iac.onPlay(() => {
      tt.showToast({ title: "开始播放" });
    });

    iac.onError((err) => {
      tt.showModal({
        title: "播放出错",
        content: err.errMsg,
        showCancel: false,
      });
    });
  },
  onUnload() {
    this.innerAudioContext && this.innerAudioContext.destroy();
  },
  play() {
    this.innerAudioContext.play();
  },
});

【代码示例 2】:播放本地临时路径音频文件

<!-- index.ttml -->
<button type="primary" bindtap="play">播放</button>
// index.js
Page({
  onShow: function () {
    let iac = (this.innerAudioContext = tt.createInnerAudioContext());

    iac.startTime = 0;
    iac.autoplay = false;
    iac.loop = false;
    iac.obeyMuteSwitch = false;

    iac.onCanplay(() => {
      console.log("onCanplay", "音频进入可以播放状态,但不保证后面可以流畅播放");
    });

    iac.onPlay(() => {
      tt.showModal({
        title: "开始播放",
        content: `音频地址:${iac.src}`,
      });
    });

    iac.onError((err) => {
      tt.showModal({
        title: "播放出错",
        content: err.errMsg,
        showCancel: false,
      });
    });
  },
  onUnload() {
    this.innerAudioContext && this.innerAudioContext.destroy();
  },
  play() {
    tt.downloadFile({
      url: "https://sf1-ttcdn-tos.pstatp.com/obj/developer/sdk/0000-0001.mp3", // 待下载的音频文件,需要在小程序开发者平台配置downloadFile 合法域名
      success: (res) => {
        if (res.statusCode === 200) {
          // 下载到本地的文件临时地址
          console.log("下载成功", res.tempFilePath);
          this.innerAudioContext.src = res.tempFilePath;
          this.innerAudioContext.play();
        }
      },
      fail: (err) => {
        console.log("下载失败", res.errMsg);
        tt.showModal({
          title: "下载失败",
          content: err.errMsg,
          showCancel: false,
        });
      },
    });
  },
});

Bug & Tip

暂无

点击纠错
评价此篇文档