Skip to content

Commit ba44f97

Browse files
author
Dario Segura
committed
[APPLE] Delays audio context creation to avoid autoplay restrictions
1 parent a913cf4 commit ba44f97

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

src/service/apple/AppleService.js

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -87,16 +87,6 @@ export class AppleService extends Service {
8787
});
8888

8989
Object.keys(MusicKit.Events).forEach(key => this._registerPlayerEvent(MusicKit.Events[key]));
90-
91-
this.mAudioContext = new (window.AudioContext || window.webkitAudioContext)();
92-
this.mAudioSource = this.mAudioContext.createMediaElementSource(this.mAPI.player.audio);
93-
// this.mAudioSource.connect(this.mAudioContext.destination);
94-
95-
// always delay the audio output by 0.2 seconds to account for speaker connections
96-
const delay = this.mAudioContext.createDelay(5.0);
97-
delay.delayTime.value = 0.2;
98-
this.mAudioSource.connect(delay);
99-
delay.connect(this.mAudioContext.destination);
10090
}
10191

10292
async authorize() {
@@ -141,6 +131,11 @@ export class AppleService extends Service {
141131

142132
async play(song = null) {
143133
await this.authorize();
134+
if (!this.mAudioContext || !this.mAudioSource) {
135+
this._setupWebAudio();
136+
await waitOneTick();
137+
}
138+
144139
if (this.isPlaying) {
145140
if (!song) {
146141
return true;
@@ -402,4 +397,16 @@ export class AppleService extends Service {
402397
}
403398
// console.log([event, info]); // eslint-disable-line
404399
}
400+
401+
_setupWebAudio() {
402+
this.mAudioContext = new (window.AudioContext || window.webkitAudioContext)();
403+
this.mAudioSource = this.mAudioContext.createMediaElementSource(this.mAPI.player.audio);
404+
// this.mAudioSource.connect(this.mAudioContext.destination);
405+
406+
// always delay the audio output by 0.2 seconds to account for speaker connections
407+
const delay = this.mAudioContext.createDelay(5.0);
408+
delay.delayTime.value = 0.2;
409+
this.mAudioSource.connect(delay);
410+
delay.connect(this.mAudioContext.destination);
411+
}
405412
}

0 commit comments

Comments
 (0)