node.js - How to stream a media file from server to client side for example an mp3 audio file in my case in loopback 4 nodejs?
问题描述
I have loopback 4 - nodejs in the backend and Ionic 4 in the frontend of my mobile application. I'm storing an mp3 file on server sid and I want to stream and play it on the client-side so basically audio streaming from loopback4. So basically I'm looking for server-side code in loopback-4 which is in typescript to audio-stream a file to client. (I'm unable to use npmjs libraries since most of them are not typed and cannot be used in typescript)
解决方案
简短的回答: 我可以通过简单地提供静态文件来实现这一点,即来自服务器端的音频文件。使用我创建的端点访问它并使用前端的标签调用它。
长答案:
在环回 4 中,您可以在 application.ts 文件中找到一行代码,其中提供了服务器项目根文件夹中的公共目录。
this.static('/', path.join(__dirname, '../../public'));
同样,您可以从您想要的任何目录提供静态文件。就我而言,我从我添加到节点项目的根目录中的媒体文件夹中提供了我的文件。
this.static('/', path.join(__dirname, '../media'));
- 第二步是公开一个 API 端点,您将使用该端点向服务器发出 get 请求。您可以在服务器项目的 index.ts 文件和 app.start() 下方的代码中执行此操作。
app.static('/media', 'media', { extensions: ['mp3'] });
此处,必须添加 API 端点和节点项目根文件夹中的目录。
现在,在前端,您只需将完整的 url 添加到从节点项目访问静态文件到 html 标记的src属性。将控件属性添加到标签中,html 将为您处理一切。您可以播放、暂停、跳过等。
<音频控件#audioElement id="id1" [src]="http://localhost:3000/media/audio-files/myAudiofile.mp3">
推荐阅读
- python - 如何从 LinkedIn API 获取图片 URL(和其他字段)?
- node.js - 解密销售伙伴 API 报告
- jmeter - JMeter 无法在本地主机上发送 CSV 数据
- wordpress - 尝试在 wordpress 中安装演示内容时出现错误
- javascript - 集成vue to express的问题
- c# - 在启用 EntityFrameWorkCore 的应用程序中更改 ApplicationName
- router - 虽然我不能在vue3中使用publicPath,但我在路由器上得到404
- c# - 如何使用 WinUI 3.0 桌面应用程序的 Project Reunion 模板在 Windows 应用程序中添加相机功能?
- javascript - 为什么我的样式表交换按钮不能保持刷新?
- blazor - 如何像在 API 控制器中那样访问 Blazor WebAssembly 中的 HttpContext?