首页 > 解决方案 > 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)

标签: node.jsaudio-streamingloopbackloopback4nodejs-server

解决方案


简短的回答: 我可以通过简单地提供静态文件来实现这一点,即来自服务器端的音频文件。使用我创建的端点访问它并使用前端的标签调用它。

长答案:

  1. 在环回 4 中,您可以在 application.ts 文件中找到一行代码,其中提供了服务器项目根文件夹中的公共目录。

    this.static('/', path.join(__dirname, '../../public'));

同样,您可以从您想要的任何目录提供静态文件。就我而言,我从我添加到节点项目的根目录中的媒体文件夹中提供了我的文件。

this.static('/', path.join(__dirname, '../media'));
  1. 第二步是公开一个 API 端点,您将使用该端点向服务器发出 get 请求。您可以在服务器项目的 index.ts 文件和 app.start() 下方的代码中执行此操作。

app.static('/media', 'media', { extensions: ['mp3'] });

此处,必须添加 API 端点和节点项目根文件夹中的目录。

  1. 现在,在前端,您只需将完整的 url 添加到从节点项目访问静态文件到 html 标记的src属性。将控件属性添加到标签中,html 将为您处理一切。您可以播放、暂停、跳过等。

    <音频控件#audioElement id="id1" [src]="http://localhost:3000/media/audio-files/myAudiofile.mp3">


推荐阅读