Write a script that downloads the film Sintel and streams it into a <video>
tag.
Torrents can contain multiple files, so it’s important to select the file we want to use. We want the .mp4
file since we’re trying to play the video.
Add code to your 'ready'
handler to select the .mp4
file from the torrent.files
array. Finally, display it in the page.
torrent.on('ready', () => {
// ...previous code...
// Torrents can contain many files. Let's use the .mp4 file
const file = torrent.files.find(file => file.name.endsWith('.mp4'))
// Display the file by adding it to the DOM
file.appendTo('body', { autoplay: true, muted: true })
})
The argument to appendTo
is a CSS selector that describes an element on the page. The argument 'body'
represents the HTML <body>
tag that is present in all HTML pages.
Notice how we set the option { autoplay: true }
to make the video play automatically. We also set the option { muted: true }
so that the video will start out muted. (Modern browsers block audio that plays without user interaction, so this combination of options allows the video to start playing automatically without being blocked.)
To learn more about the appendTo
API, read the docs.
If it worked, you should see the film “Sintel” start to play back! You just played back your first torrent in the browser with WebTorrent!
If you are stuck, read the solution.
When you are ready, go to the next exercise.