使用 WebView React Native 从本地文件播放视频

Play video from local files with WebView React Native

所以这就是重点。我的设备上下载了一些文件。因为可以是视频、mp3 或 pdf,所以在 webview 上显示它会很好,所以它的预览系统会为我完成工作,我不需要下载任何外部媒体播放器。

我有这个代码 让我们假设这条路径:

const path = 'file:///Users/MyUser/Library/Developer/CoreSimulator/Devices/D18AD5B6-22D1-4F57-A162-8A1C5DBCAD7A/data/Containers/Data/Application/BF9347EB-8EDF-45CB-9CFD-08C0C8BE3D5C/Documents/song.mp3';


 <WebView
            javaScriptEnabled
            source={{ uri: path }}
            style={{ marginTop: 0 }}
          />

我的问题是当我尝试加载文件时,它总是引发此错误:

我怀疑是关于uri的路由。使用 require 也会报错(无法解析模块)

此应用仅适用于 Ios,不适用于 Android。

任何帮助将不胜感激! 提前致谢

您无法在网络视图中播放视频。请使用像 react-native-video 这样的 npm 包,它将帮助您播放带有更多控件的视频

this maybe help you, using html video/audio tag

我明白了!!! 这很艰难,但终于,我明白了。

  1. 终于用webview搞定了。我做了什么:

    <WebView source={{ html: `<html>
        <body>
           <video width="320" height="240" controls>
               <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
                Your browser does not support the video 
           </video>
        </body>
    </html>` }} />
    

有了这个,感谢@marx_tseng 我在 webview 上注入了 HTML,所以我利用了浏览器的媒体播放器。

  1. 我必须从 bundle.js 加载 video/image/mp3。当您调用 webview 时它正在加载。在此示例中,我使用 RNFetchBlob 只是指向我的文档存储在我的设备中的文件夹。

    const html = `<script src="${RNFetchBlob.fs.dirs.MainBundleDir}/bundle.js"></script> `;
    <WebView
    source={{ baseUrl: RNFetchBlob.fs.dirs.DocumentDir, html,</Webview>
    
  2. 最后,这是代码结果:

     const html = `<script 
     src="${RNFetchBlob.fs.dirs.MainBundleDir}/bundle.js"></script> `;
     <WebView
     source={{ baseUrl: RNFetchBlob.fs.dirs.DocumentDir, html,
            html: `<html>
                     <body>
                        <video width="320" height="240" controls>
                            <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
                                   Your browser does not support the video 
                         </video>
                      </body>
                   </html>`
           }}
     />
    

这里@plougsgaard 提供了这个解决方案。 https://github.com/wkh237/react-native-fetch-blob/issues/197

如果有人遇到同样的情况,我希望这个答案能有所帮助。 干杯!