Audio
Tip: If you use a game engine for development, the game engine may have adapted audio processing, and you only need to use the components in the game engine.
InnerAudio
InnerAudio The way to play audio is simple and fast, and supports streaming playback, which is suitable for playing large audio files, such as background music.
Related API
- Create:wx.createInnerAudioContext
- Play:InnerAudioContext.play
- Audio configuration:wx.setInnerAudioOption
Sample code:
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)
});Supported formats
Different audio formats may differ between iOS and Android, refer toAudio
Usage suggestions
Reuse existing audio instances
For the same sound effect, you should reuse existing audio instances instead of creating a new audio instance.
Destroy unnecessary audio instances in time
If an audio is no longer needed, you can call the InnerAudioContext.destroy() interface to destroy the instance in advance.
Limit on the number of audios played simultaneously
Due to system limitations, a maximum of 10 audios can be played simultaneously on Android. The excess will be processed lossily, which is not noticeable to developers, but developers should try to avoid playing too many audios at the same time.