Hi,
I’m trying to show some music controls using the MediaSession API. It’s works almost (Mac OS controls bar, Google Chrome) everywhere except on iOS device which is always displaying “Ionic App” while playing. I’m testing this on my real Iphone. The code which I’m using seems to have some effects because while I’m using it, previous and next buttons appears.
Here’s my background modes config :
Here’s my code
import React, { useEffect, useRef, useState } from 'react';
import { IonButton, IonItem, IonLabel } from '@ionic/react';
const MediaPlayer: React.FC = () => {
const audioRef = useRef<HTMLAudioElement | null>(null);
const [isPlaying, setIsPlaying] = useState(false);
// Fonction pour démarrer la lecture de l'audio
const playAudio = () => {
if (audioRef.current) {
audioRef.current.play().then(() => {
// Mettre à jour les métadonnées après le début de la lecture
if ('mediaSession' in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: 'Track',
artist: 'Artist',
album: 'Album'
});
}
});
setIsPlaying(true);
}
};
// Fonction pour mettre en pause l'audio
const pauseAudio = () => {
if (audioRef.current) {
audioRef.current.pause();
setIsPlaying(false);
}
};
// Utilisation de l'API Media Session
useEffect(() => {
console.log('Initialisation de l\'API Media Session');
if ('mediaSession' in navigator) {
navigator.mediaSession.setActionHandler('play', () => {
playAudio();
});
navigator.mediaSession.setActionHandler('pause', () => {
pauseAudio();
});
}
}, []);
return (
<IonItem>
<IonLabel>Lecteur Audio</IonLabel>
<audio ref={audioRef} src="/files/pwop.mp3" preload="metadata" />
{isPlaying ? (
<IonButton onClick={pauseAudio}>Pause</IonButton>
) : (
<IonButton onClick={playAudio}>Play</IonButton>
)}
</IonItem>
);
};
export default MediaPlayer;
Did you know how I can achieve this please ? Thanks you very much !