Solve the problem that IOS audio cannot play

Time:2021-1-15

In IOS, audio can’t pass through directly audio.play () to play, the user needs to execute it in the click event or touch event audio.play () to play.

Ajax callback audio.play () the music doesn’t play properly.

The user clicks the button and plays the corresponding successful or failed music after the server returns the data. The test results show that the music cannot be played normally in IOS. Guess that audio in IOS can’t play ()

The following is a record of the problem solving process of playing music in Ajax callback in IOS

Solution 1: reduce the volume

After the user clicks time, set the audio volume to 0, and after success, set the volume to 1; volume can control the audio volume, and the value range is 0 ~ 1


audio.volume=number

I found that the music can be muted in Chrome’s mobile phone mode, but the volume can’t be controlled in IOS. OK, this is blocked by IOS. Give up

Solution 2: pause immediately after playing

The user will play the music immediately after clicking the button, and continue to play after Ajax returns the data. The test can play normally. Some of the codes are as follows:

//User click event
if ( this.isIOS ()) {// IOS doesn't need to handle Android alone
 this.$refs.audio.play()
 this.$refs.audio.pause()
}

//Events after successful Ajax
 this.$refs.audio.pause()
 this.$refs.audio.currentTime = 0
 this.$refs.audio.play()

Because it’s a Vue project, there’s this. $refs in the code. Don’t mind;

summary

In IOS, if you need to play music or video, you need to trigger the event manually and call. Play() to play (autoplay or direct. Play() cannot be triggered directly);

If you need to play music in the Ajax callback function, you need to pause playing music immediately after the user triggers the event, and then. Play () can be played in the callback function. Otherwise, the playback is not successful in IOS.