Reputation: 21
I'm using four HTML audio elements in a page in a React application and would like to get the lock screen media controls (play, pause, next, previous etc.) to show up on iPhone, which I'd like to customise with Media Session API. It does show up sometimes but for some reason it's intermittent, maybe coming up one in four times. When I only use one audio element it always comes up.
And for some reason it will always come up when I click play, pause and then play again before locking the screen.
This is the code (I've removed the URLs for the audio sources but they're correct on my side)
class App extends Component<IAppProps, IAppState> {
private vocals: HTMLAudioElement;
private other: HTMLAudioElement;
private bass: HTMLAudioElement;
private drums: HTMLAudioElement;
constructor(props: any) {
super(props);
this.vocals = new Audio();
this.other = new Audio();
this.bass = new Audio();
this.drums = new Audio();
this.vocals.src = '';
this.other.src = '';
this.bass.src = '';
this.drums.src = '';
this.vocals.load();
this.other.load();
this.bass.load();
this.drums.load();
if ('mediaSession' in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: 'Unforgettable',
artist: 'Nat King Cole',
album: 'The Ultimate Collection (Remastered)',
artwork: [
{ src: 'https://dummyimage.com/96x96', sizes: '96x96', type: 'image/png' },
{ src: 'https://dummyimage.com/128x128', sizes: '128x128', type: 'image/png' },
{ src: 'https://dummyimage.com/192x192', sizes: '192x192', type: 'image/png' },
{ src: 'https://dummyimage.com/256x256', sizes: '256x256', type: 'image/png' },
{ src: 'https://dummyimage.com/384x384', sizes: '384x384', type: 'image/png' },
{ src: 'https://dummyimage.com/512x512', sizes: '512x512', type: 'image/png' },
]
});
}
this.state = {
playbackState: 'paused',
}
}
handlePlayClick = () => {
const { playbackState } = this.state;
if (playbackState === 'paused') {
this.setState({ playbackState: 'playing'});
navigator.mediaSession.playbackState = 'playing';
this.vocals.play();
this.other.play();
this.bass.play();
this.drums.play();
} else {
this.setState({ playbackState: 'paused'});
navigator.mediaSession.playbackState = 'paused';
this.vocals.pause();
this.other.pause();
this.bass.pause();
this.drums.pause();
}
}
render() {
return (
<div className="App">
<button onClick={this.handlePlayClick}>{this.state.playbackState === 'paused' ? 'PLAY' : 'PAUSE'}</button>
</div>
);
}
}
Upvotes: 2
Views: 185