我正在尝试使用 ionic cordova Media 和 File 插件在 ios 设备上录制语音笔记,并将其推送到 firebase 存储。
On android is working well.
这是我的代码:
首先我创建了 init()
函数
init(): Promise < any > {
this.date = moment().format('x');
return new Promise((resolve, reject) => {
let currentFile: File;
this.fileName = this.date + `-rnb.mp3`;
this.file.createFile(this.platform.is('ios') ? cordova.file.tempDirectory : cordova.file.dataDirectory, this.fileName, true).then((result) => {
this.current_file_playing = this.createAudioFile(this.storageDirectory, this.fileName);
resolve();
}, (e) => {
console.log(JSON.stringify(e, null, 2));
reject(e);
})
});
}
this.storageDirectory
它是在提供程序 constructor()
中定义的变量,等于目录路径,具体取决于平台。这是以下代码:
this.platform.ready().then(() => {
if (this.platform.is('ios')) {
this.storageDirectory = this.file.tempDirectory;
} else if (this.platform.is('android')) {
this.storageDirectory = this.file.externalDataDirectory;
}
});
然后 record()
函数是录音按钮的监听器
record(){
return new Promise((resolve,reject)=>{
this.init().then((media:Media) => {
try {
this.startRecording(media);
resolve(media);
} catch (e) {
console.log(e);
}
});
});
}
这是 startRecording()
函数:
startRecording(mediaPlugin: any) {
this.current_file_playing.startRecord();
}
此外,stopRecording()
函数是停止按钮的监听器:
stopRecording(mediaPlugin: any) {
return new Promise((resolve,reject)=>{
this.current_file_playing.stopRecord();
this.current_file_playing.play();
this.current_file_playing.setVolume(0.0); //trick
this.saveFirebase().then((downloadUrl) => {
resolve(downloadUrl);
});
});
}
最后,这就是我使用 saveFirebase()
函数
saveFirebase() {
return new Promise((resolve, reject) => {
let storageRef = firebase.storage().ref();
let metadata = {
contentType: 'audio/mp3',
};
this.file.readAsDataURL(this.storageDirectory, this.fileName).then((file) => {
let voiceRef = storageRef.child(`voices/${this.fileName}`).putString(file, firebase.storage.StringFormat.DATA_URL);
voiceRef.on(firebase.storage.TaskEvent.STATE_CHANGED, (snapshot) => {
console.log("uploading");
}, (e) => {
console.log('inside the error');
reject(e);
console.log(JSON.stringify(e, null, 2),'this.error');
}, () => {
var downloadURL = voiceRef.snapshot.downloadURL;
resolve(downloadURL);
});
});
});
}
saveFirebase()
函数的解释
首先,我使用 this.file.readAsDataURL(...)
将文件转换为 base64,然后使用 putString
推送 Firebase 存储方法。
The audio file is successfully pushed to Firebase Storage, But with 0 Byte size. That is mean to pushing to Firebase is working well, but the recording voice to the file is not working.
The audio files that have size is recorded from android device.
有人知道我的问题是什么吗?
谢谢。
最佳答案
问题是:
音频文件应该是.wav。所以当我把音频的类型改成wav的时候。
let metadata = {
contentType: 'audio/wav',
};
this.fileName = this.date + `-rnb.mp3`;
它对我有用。
谢谢。
关于ios - 使用 ionic 媒体插件在 IOS 上录制语音笔记不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48824291/