Ionic 7 – 下载并使用音频控件播放mp3文件

huangapple go评论78阅读模式
英文:

Ionic 7 - Download and play mp3 file with audio controls

问题

I want my application to download and store them.

然后,用户可以选择要播放的文件。我希望它就像Spotify一样。一列音频,用户点击播放音频。

我正在使用Ionic的本地文件插件将文件保存在this.file.dataDirectory

下载文件

this.http.sendRequest(url, { method: "get", responseType: "arraybuffer" }).then(
    res => {
        let blob = new Blob([res.data], { type: 'audio/mp3' });
        this.saveFile(blob);
    }
);

保存文件

this.file.createFile(folderPath, fileName, true).then(
    _ => {
        if (blob == null) {
            console.error("Downloaded file is null");
            reject(false);
        } else {
            this.file.writeFile(folderPath, fileName, blob, { replace: true }).then(_ => {
                console.log("File created");
            });
        }
    })

我收到了"文件已创建"的消息。很好!但是,我在"内部存储 -> Android -> io.ionic.starter -> data"中看不到这些文件,但如果我使用 this.file.checkFile(folderPath, filename),它会返回true

播放音频

这是噩梦的部分。当我将URL传递给JavaScript的Audio时,它可以正常工作,就像:

let audioAsset = new Audio(audioLink);
audioAsset.play();

但是它不适用于本地文件!

不允许加载本地资源:file:///data/user/0/io.ionic.starter/files/myfile.mp3

我尝试了NativeAudio,但我收到了"FileNotFoundException"。当我的音频文件已经添加到assets文件夹中时,它可以工作,但对于我下载到"dataDirectory"的文件则不行。

一些论坛提到了MediaObject,就像这个。然而,现在没有@ionic-native/media包。它似乎现在是一个企业功能

这应该是一个非常简单的任务,但在Ionic中变得非常棘手!有谁可以帮助我?

英文:

My server has some mp3 files stored.

I want my application to download and store them.

Then, user can select which file to play. I'd like it to be just like Spotify. A list of audios, and user clicks to play the audio.

I'm using Ionic's native File plugin to save the file, in this.file.dataDirectory

Downloading files

this.http.sendRequest(url, {method: "get", responseType: "arraybuffer"}).then(
    res => {
      let blob = new Blob([res.data], {type: 'audio/mp3'});
      this.saveFile(blob);
    }
);

Saving files

this.file.createFile(folderPath, fileName, true).then(
    _ => {
      if(blob == null) {
        console.error("Downloaded file is null");
        reject(false);
      } else {
        this.file.writeFile(folderPath, fileName, blob, {replace: true}).then(_ => {
          console.log("File created");
        });
      }
})

I'm getting the "file created" message. Nice! However, I cannot see those files in "Internal Storage -> Android -> io.ionic.starter -> data", but if I use the this.file.checkFile(folderPath, filename), it returns true.

Playing the audio

This is the nightmare part. When I give an URL to Javascript's Audio, it works nicely, just like:

let audioAsset = new Audio(audioLink);
audioAsset.play();

But it doesn't work with local files!

Not allowed to load local resource: file:///data/user/0/io.ionic.starter/files/myfile.mp3

I tried NativeAudio, but I get the "FileNotFoundException". It worked when I had my audio files already added in assets folder, but not to those I download to "dataDirectory".

Some forums mention MediaObject, just like THIS ONE. However, there is no @ionic-native/media package anymore. It seems to be an Enterprise Feature now.

This should be a very simple task, but it is becoming a nightmare with Ionic! Can anyone help me?

答案1

得分: 1

解决了数小时的问题。以下是一些提示,可使Ionic开发者的生活更轻松。

下载文件: 使用本机HTTP

import { HTTP } from '@awesome-cordova-plugins/http/ngx';

constructor(private http: HTTP) { }

this.http.sendRequest(url, {method: "get", responseType: "arraybuffer"}).then(
  res => { this.saveFile(new Blob([res.data], {type: 'audio/mp3'})) }
);

保存文件: 使用本机文件externalApplicationStorageDirectory作为文件夹

import { File } from '@awesome-cordova-plugins/file/ngx';

constructor(private file: File) {}

saveFile(blob) {
  let path = this.file.externalApplicationStorageDirectory;
  let filename = 'myfile.mp3';
  this.file.writeFile(path, filename, blob, {replace: true}).then(res => {/*code here*/})
}

最后,播放音频: 原来Media不仅是企业功能。这里是社区版本。很难找到。干得好,Ionic...

import { Media, MediaObject } from '@awesome-cordova-plugins/media/ngx';
import { File } from '@awesome-cordova-plugins/file/ngx';

constructor(private media: Media, private file: File) {}

playSound() {
  let path = this.file.externalApplicationStorageDirectory;
  let filepath = `${path}/myfile.mp3`;
  let file: MediaObject = this.media.create(filepath);
  file.play();
}

不要忘记设置权限。这是我的:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

奖励环节: 通知栏上的音频控件很棒,对吧?这里有一个cordova的MediaSession API插件 这里。非常感谢这个家伙

英文:

Solved the issue after several hours. Here are some hints to make the Ionic developer's life easier.

Downloading a file: Use Native HTTP

import { HTTP } from &#39;@awesome-cordova-plugins/http/ngx&#39;;

constructor(private http: HTTP) { }

this.http.sendRequest(url, {method: &quot;get&quot;, responseType: &quot;arraybuffer&quot;}).then(
  res =&gt; { this.saveFile(new Blob([res.data], {type: &#39;audio/mp3&#39;)) }
);

Saving a file: use Native File and externalApplicationStorageDirectory as your folder

import { File } from &#39;@awesome-cordova-plugins/file/ngx&#39;;

constructor(private file: File) {}

saveFile(blob) {
  let path = this.file.externalApplicationStorageDirectory;
  let filename = &#39;myfile.mp3&#39;;
  this.file.writeFile(path, filename, blob, {replace: true}).then(res =&gt; {/*code here*/})
}

And finally, PLAYING THE AUDIO: Turns out that Media was not only an Enterprise feature. HERE is the community version. It was hard to find. Bad job, Ionic...

import { Media, MediaObject } from &#39;@awesome-cordova-plugins/media/ngx&#39;;
import { File } from &#39;@awesome-cordova-plugins/file/ngx&#39;;

constructor(private media: Media, private file: File) {}

playSound() {
  let path = this.file.externalApplicationStorageDirectory;
  let filepath = `${path}/myfile.mp3`;
  let file: MediaObject = this.media.create(filepath);
  file.play();
}

And DO NOT forget to set the permissions. Here are mine:

&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.READ_MEDIA_AUDIO&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.POST_NOTIFICATIONS&quot;/&gt;

BONUS ROUND: Audio controls on the notification bar are awesome, right? There is a MediaSession API plugin for cordova HERE. Many thanks to THIS GUY too.

huangapple
  • 本文由 发表于 2023年6月8日 04:09:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426788.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定