Play audio files using JavaScript

New licenses for WebViewer Audio are no longer offered.

Initial setup

Before you begin, make sure your development environment includes Node.js and npm.

Install

sh

1npm install @pdftron/webviewer-audio

How to use

Here is an example of how WebViewer and WebViewer-audio could be integrated into your application.

JavaScript

1import React, { useRef, useEffect } from 'react';
2import WebViewer from '@pdftron/webviewer';
3import { initializeAudioViewer } from '@pdftron/webviewer-audio';
4
5const App = () => {
6 const viewer = useRef(null);
7
8 useEffect(() => {
9 WebViewer(
10 {
11 path: '/webviewer/lib',
12 },
13 viewer.current,
14 ).then(async instance => {
15 // Extends WebViewer to allow loading media files (.mp3, .mp4, ogg, webm, etc.)
16 const {
17 loadAudio,
18 } = await initializeAudioViewer(
19 instance,
20 {
21 license: '---- Insert commercial license key here after purchase ----',
22 }
23 );
24
25 // Load a media element at a specific url. Can be a local or public link
26 // If local it needs to be relative to lib/ui/index.html.
27 // Or at the root. (eg '/audio.mp3')
28 const audioUrl = '/audio.mp3';
29 loadAudio(audioUrl);
30 });
31 }, []);
32
33 return (
34 <div className="App">
35 <div className="webviewer" ref={viewer} />
36 </div>
37 );
38}
39
40export default App;

Loading as a Script Tag

If your environment can not import WebViewer Video from the module, you can instead include WebViewer Video as a script tag. Simply, take the file node_modules/@pdftron/webviewer-audio/dist/main.js and add it to your project's html page.

HTML

1<head>
2 <!-- ... -->
3 <!-- main.js can be renamed -->
4 <script src="./main.js"></script>
5</head>

This will add the object WebViewerAudio to the window. This object contains initializeAudioViewer. So the previous code can be changed to:

JavaScript

1// ...
2const {
3 loadAudio,
4} = await window.WebViewerAudio.initializeAudioViewer(
5 instance,
6 {
7 license: '---- Insert commercial license key here after purchase ----',
8 }
9);
10// ...

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales