Skip to content

Commit

Permalink
feat(plugins): MagicPlayer > fix autoplay issue
Browse files Browse the repository at this point in the history
  • Loading branch information
ChristophJeworutzki committed Oct 11, 2024
1 parent cd6fb3e commit f3b2472
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
32 changes: 24 additions & 8 deletions packages/plugins/MagicPlayer/src/components/MagicPlayer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
import {
useElementVisibility,
useEventListener,
defaultWindow,
} from '@vueuse/core'
import { usePlayerVideoApi } from '../composables/private/usePlayerVideoApi'
import { usePlayerMediaApi } from '../composables/private/usePlayerMediaApi'
import { usePlayerRuntime } from '../composables/private/usePlayerRuntime'
Expand All @@ -47,6 +51,8 @@ const props = withDefaults(defineProps<MagicPlayerProps>(), {
const playerRef = ref<HTMLDivElement | undefined>(undefined)
const videoRef = ref<HTMLVideoElement | undefined>(undefined)
const isVisible = useElementVisibility(playerRef)
const { playing, muted } = usePlayerMediaApi({
id: props.id,
mediaRef: videoRef,
Expand All @@ -65,13 +71,23 @@ const { onMouseenter, onMouseleave, play, pause } = usePlayerVideoApi({
playerRef: playerRef,
})
useIntersectionObserver(
playerRef,
([{ isIntersecting }]) => {
if (!isIntersecting && playing.value) {
pause()
} else if (isIntersecting && !playing.value && props.autoplay) {
function onWindowFocus() {
if (isVisible.value && !playing.value && props.autoplay) {
play()
}
}
// Auto play when window is focused
useEventListener(defaultWindow, 'focus', onWindowFocus)
// Auto play when element is visible
watch(
isVisible,
(value) => {
if (value && !playing.value && props.autoplay) {
play()
} else if (!value && playing.value) {
pause()
}
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,7 @@ export function usePlayerMediaApi(args: UsePlayerMediaApiArgs) {

if (isPlaying) {
const playPromise = el.play()
if (playPromise !== undefined)
playPromise.catch((error) => {
console.warn('Playback error:', error)
})
if (playPromise !== undefined) playPromise.catch((error) => {})
} else {
el.pause()
}
Expand Down

0 comments on commit f3b2472

Please sign in to comment.