There is only one way to play audio in a mini-game, using the InnerAudioContext.

Play with InnerAudioContext

Through wx. CreateInnerAudioContext () interface can create an audio example innerAudioContext, through this example can play audio.

var audio = wx.createInnerAudioContext();
audio.src = 'audio/bgm.mp3';
audio.play();
Copy the code

On IOS, the mute button is set by default. If you want to be able to play sound even when muted, set obeyMuteSwitch to false.

Auto play and loop play

Set the autoplay and loop properties to automatically play and loop the audio, generally applicable to background music.

var bgm = wx.createInnerAudioContext();
bgm.autoplay = true;
bgm.loop = true;
bgm.src = 'audio/bgm.mp3';
Copy the code

Handles audio interrupt events

Audio interrupt events are the events that are triggered when audio is interrupted by the system during the game. Audio interrupt events into interrupts the start and end, respectively using wx. OnAudioInterruptionBegin () and wx onAudioInterruptionEnd () to listen.

The following events trigger the audio interrupt start event: the phone is transferred, the alarm goes off, the system is alerted, and a voice/video call request from a wechat friend is received. After being interrupted, all audio in the small program will be suspended, and can not play successfully before the end of the interruption.

After the end of the interrupt, the audio will not automatically continue to play, if the small game has background music, you need to listen to the end of the audio interrupt event, and call the background music to continue to play after receiving the end of the interrupt event.

wx.onAudioInterruptionEnd(function(){
    bgm.play();
})
Copy the code

If the logic of the mini-game is heavily dependent on music playing, you need to pause the game when the audio starts to break.

wx.onAudioInterruptionBegin(function(){// pause the game})Copy the code

Compatibility Note

Currently, the audio formats fully supported by the two platforms include MP3, AAC and WAV. Other formats have system differences and are not guaranteed to be supported.

Reuse an existing audio instance

Instead of creating a new audio instance, reuse an existing audio instance for the same sound effect.

Destroy unwanted audio instances in a timely manner

If an audio no longer need to use, you can call InnerAudioContext. Destroy early destruction of the instance () interface.

Limit the amount of audio that can be played simultaneously on Android

Due to system limitations, a maximum of 10 audio files can be played at the same time on Android. The excess audio files will be damaged and will not be perceived by developers, but developers should try to avoid playing too many audio files at the same time.

The content about the small program audio playback for you to introduce here, the next section we will introduce you to the file system related content.