Skip to content

音訊

提示:如果你使用遊戲引擎進行開發,遊戲引擎可能已經適配了音訊處理,你只需要使用遊戲引擎中的元件。

InnerAudio

InnerAudio 播放音訊的方式簡便快捷,且支援串流播放,適用於播放較大音訊文件,例如背景音樂。

相關API

示例代碼:

js
const innerAudioContext = wx.createInnerAudioContext();
innerAudioContext.src = "https://wx_test.mp3"; // Replace with your own link
innerAudioContext.loop = true; // Set to loop playback
// innerAudioContext.autoplay = true; // Automatically start playing when ready
innerAudioContext.onError((res) => {
  console.log("Error", res);
});
innerAudioContext.onPlay(() => {
  console.log("Playback started");
});
innerAudioContext.onCanplay(() => {
  console.log("Ready to play");
  innerAudioContext.play(); // Start playback
});
innerAudioContext.onStop(() => {
  console.log("Playback stopped");
});
innerAudioContext.onEnded(() => {
  console.log("Playback ended");
});
innerAudioContext.pause(); // Pause
innerAudioContext.stop(); // Stop
innerAudioContext.destroy(); // Release audio resources

wx.onShow(() => {
  innerAudioContext.play(); // Resume playback when the mini game returns to the foreground
});

wx.onAudioInterruptionEnd(function () {
  innerAudioContext.play(); //Resume playback after being interrupted by another event (e.g., a phone call)
});

支援的格式

不同音訊格式在 iOS 和 Android 會有差異,參考音訊

使用建議

復用已有的音訊實例

對於相同的音效,應該重複使用已有的音訊實例,而不是重新建立一個音訊實例。

及時銷毀不需要的音訊實例

如果一個音訊不再需要使用了,可以呼叫 InnerAudioContext.destroy() 介面提前銷毀這個實例。

同時播放的音訊數量限制

由於系統限制,在 Android 上同時播放最多 10 個音頻,超過的部分會做有損處理,對開發者來說不感知,但開發者應盡量避免同時播放過多音頻。