我可以将Media Object从离子转换为Blob吗?

时间:2018-01-07 14:06:48

标签: javascript angular ionic-framework

我尝试将Ionic中记录的MediaObject转换为Blob,但我没有成功。 有谁知道怎么做?

https://ionicframework.com/docs/native/media/

%CONDA_ENV_PATH%\

1 个答案:

答案 0 :(得分:0)

您需要先获取文件的路径,然后将其转换为blob。

  1. 获取文件路径:

为避免几次iOS怪癖,我首先使用文件插件的createFile()方法创建一个临时文件。它返回一个承诺,该承诺解析为您需要通过toInternalURL()方法转换为cordova(CDV)文件路径的路径。在创建临时文件之后,将创建媒体对象。它不应具有"file://"前缀。例如

this.filePlugin.createFile(this.file.tempDirectory, YOUR_FILE_NAME, true).then(filePath => { 
    audio: MediaObject = this.media.create(this.file.tempDirectory.replace(/^file:\/\//, '') + YOUR_FILE_NAME);
    // your recording logic here...
    // once the recording is finished:
    cdvPath = filePath.toInternalURL(); 
} 
  1. 完成录制后,我们将通过以下功能使用该路径创建blob。使用上面获得的cdvPath进行调用即可完成操作。 (要注意解决对象的事实!):
makeFileIntoBlob(_filePath) {
    return new Promise((resolve, reject) => {
        let fileName, fileExtension = "";
        this.file.resolveLocalFilesystemUrl(_filePath)
            .then(fileEntry => {
                let {name, nativeURL} = fileEntry;
                // get the path..
                let path = nativeURL.substring(0, nativeURL.lastIndexOf("/"));
                fileName = name;
                // if you already know the file extension, just assign it to           // variable below
                fileExtension = fileName.match(/\.[A-z0-9]+$/i)[0].slice(1);
                // we are provided the name, so now read the file into a buffer
                return this.file.readAsArrayBuffer(path, name);
            })
            .then(buffer => {
                // get the buffer and make a blob to be saved
                let medBlob = new Blob([buffer], {
                    type: `audio/${fileExtension}`
                });

                // pass back blob and the name of the file for saving
                // into fire base
                resolve({ blob: medBlob, blobName: name});
            })
            .catch(e => reject(e));
    });
}