Parth Mehta
Parth Mehta

Reputation: 25

How to stop PDFTron Webviewer Auido from playing in background even after switching files?

I'm working on a React project with a tree grid. I have a bunch of rows with files, associated to pdf, mp3, mp4 file types which live in a S3 bucket. Currently using a pre-signed url to display these files using the PDFTron Webviewer. However, when I load an audio file, hit play, switch to a different file within the tree grid, the audio continues to play. Similarly I have a video file as well, which works perfectly fine. I hit play, watch the video, halfway through the video I switch to a different file and the audio/video stops right there; works perfectly fine. I'm not sure why the audio file continues to play audio in background on switch...

I tried the onPause() event from the documentation provided here, but that did not help.

Also, I tried to return a cleanup function within the useEffect, which didn't help either...

useEffect(() => {
 let audioInstance: any = null; 
 let videoInstance: any = null; 

 WebViewer( ..... )
.
.
.

if (isAudioOnly) {
  audioInstance = await loadAudio(fileUrl);
} else {
  videoInstance = await loadVideo(fileUrl);
}

return () => {
  if (audioInstance) {
    audioInstance.stop();
  }
  if (videoInstance) {
    videoInstance.stop();
  }
 };
}, [isAudioOnly, withThumbnail, fileUrl]);

Any ideas on how to resolve this issue?

Below is my original component:

import { useEffect, useRef } from 'react';
import WebViewer from '@pdftron/webviewer';
import { initializeVideoViewer } from '@pdftron/webviewer-video';
import { initializeAudioViewer } from '@pdftron/webviewer-audio';

export type MediaViewerProps = {
  isAudioOnly: boolean;
  withThumbnail?: boolean;
  fileUrl: string;
};

const MediaViewer = ({
  isAudioOnly,
  withThumbnail,
  fileUrl
}: MediaViewerProps) => {
  const mediaViewer = useRef<HTMLDivElement>(null);

  useEffect(() => {
    WebViewer(
      {
        path: '/dist/webviewer/public',
        disabledElements: [
          'notesPanel',
          'applyAllButton',
          'toolsButton',
        ]
      },
      mediaViewer.current as never
    ).then(async (instance) => {
      const { Waveform, loadAudio } = await initializeAudioViewer(instance, {
        license
      });

      const { loadVideo } = await initializeVideoViewer(instance, {
        license,
        AudioComponent: Waveform
      });

      if (isAudioOnly) {
        loadAudio(fileUrl);
      } else {
        loadVideo(fileUrl);
      }
    });
  }, [isAudioOnly, withThumbnail, fileUrl]);

  return (
    <div
      className="webviewer"
      ref={mediaViewer}
      style={{ width: '100%', height: '100%' }}
    />
  );
};

export default MediaViewer;

PS: Audio only stops after refreshing the page...

Upvotes: 0

Views: 44

Answers (0)

Related Questions