-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMediaSession.jsx
95 lines (86 loc) · 2.31 KB
/
MediaSession.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { Component } from 'react'
import PropTypes from 'prop-types'
class MediaSession extends Component {
constructor (props) {
super()
this.setActions(props)
this.setMetadata(props)
}
setActions (props) {
if ('mediaSession' in navigator) {
navigator.mediaSession.setActionHandler('play', props.onPlay)
navigator.mediaSession.setActionHandler('pause', props.onPause)
navigator.mediaSession.setActionHandler(
'seekbackward',
props.onSeekBackward
)
navigator.mediaSession.setActionHandler(
'seekforward',
props.onSeekForward
)
navigator.mediaSession.setActionHandler(
'previoustrack',
props.onPlayPrev
)
navigator.mediaSession.setActionHandler('nexttrack', props.onPlayNext)
}
}
setMetadata (props) {
const { title, artist, album, image, artwork } = props
const artworkReal = artwork?.length
? artwork
: image?.length
? [
{
src: image,
sizes: '512x512',
type: 'image/png'
}
]
: undefined
navigator.mediaSession.metadata = new window.MediaMetadata({
title,
artist,
album,
artwork: artworkReal
})
}
componentDidUpdate (prevProps) {
if (
this.props.onSeekBackward !== prevProps.onSeekBackward ||
this.props.onSeekForward !== prevProps.onSeekForward ||
this.props.onPlayPrev !== prevProps.onPlayPrev ||
this.props.onPlayNext !== prevProps.onPlayNext
) {
this.setActions(this.props)
}
if (
this.props.title !== prevProps.title ||
this.props.artist !== prevProps.artist ||
this.props.album !== prevProps.album
) {
this.setMetadata(this.props)
}
}
componentWillUnmount () {
// Set all actions and metadata to undefined
this.setActions({})
this.setMetadata({})
}
render = () => null
}
MediaSession.defaultProps = {}
MediaSession.propTypes = {
title: PropTypes.string,
artist: PropTypes.string,
album: PropTypes.string,
image: PropTypes.string,
artwork: PropTypes.array,
onPlay: PropTypes.func,
onPause: PropTypes.func,
onPlayPrev: PropTypes.func,
onPlayNext: PropTypes.func,
onSeekBackward: PropTypes.func,
onSeekForward: PropTypes.func
}
export default MediaSession