- 官方给出的示例通过
appendTo
函数渲染文件对象,通过torrent.files
的元素对象调用:
const WebTorrent = require('webtorrent')
const client = new WebTorrent()
// Sintel, a free, Creative Commons movie
const torrentId = 'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent'
client.add(torrentId, function (torrent) {
// Torrents can contain many files. Let's use the .mp4 file
const file = torrent.files.find(function (file) {
return file.name.endsWith('.mp4')
})
// Display the file by adding it to the DOM.
// Supports video, audio, image files, and more!
file.appendTo('body')
})
- appendTo将调用append函数
- 调用renderMedia函数
MEDIASOURCE_EXTS.includes(extname) ? renderMediaSource() : VIDEO_EXTS.includes(extname) ? renderMediaElement("video") : AUDIO_EXTS.includes(extname) ? renderMediaElement("audio") : IMAGE_EXTS.includes(extname) ? renderImage() : IFRAME_EXTS.includes(extname) ? renderIframe() : tryRenderIframe()
使用了三元运算符来根据文件扩展名(extname)决定如何渲染不同类型的媒体内容。它依次检查文件扩展名,并调用相应的渲染函数。- 其中数组定义如下:
, VIDEOSTREAM_EXTS = [".m4a", ".m4b", ".m4p", ".m4v", ".mp4"]
, MEDIASOURCE_VIDEO_EXTS = [".m4v", ".mkv"