Ionic 3二次录音后音频无法播放问题求助
解决Ionic 3中@ionic-native/media第二次录音无声音的问题
嘿,我一眼就瞅出问题所在了——你没正确释放MediaObject的资源!第一次录音后,音频资源还被旧的Media实例占着,第二次录音时虽然生成了新文件,但实际录制的音频数据根本没写进去,最后出来的就是个空壳文件,自然播放没声音。
问题根源拆解
你的代码里有几个核心问题:
- 每次停止录音后,没调用
release()释放MediaObject资源,导致音频设备被占用,后续录音无法正常写入数据 - 第二次录音时,哪怕重新赋值了
this.audio,但旧实例没释放的话,会出现资源冲突 - 播放音频时也没处理资源释放,长期下来还会导致内存泄漏
修复后的完整代码
我帮你调整了关键逻辑,重点补上了资源释放的步骤,同时优化了流程:
// 变量部分保持不变,以下是修改后的核心函数 startRecord() { // 先释放之前可能残留的Media资源 if (this.audio) { this.audio.release(); } this.recordingMessage = "Device is preparing to record..."; const timestamp = new Date(); // 统一生成唯一文件名,避免重复代码 this.fileName = `record${timestamp.getDate()}${timestamp.getMonth()}${timestamp.getFullYear()}${timestamp.getHours()}${timestamp.getMinutes()}${timestamp.getSeconds()}.3gp`; if (this.platform.is('ios')) { this.filePath = this.file.dataDirectory + this.fileName; } else if (this.platform.is('android')) { this.filePath = this.file.dataDirectory + this.fileName; console.log("recording file = " + this.filePath); } // 创建全新的Media实例 this.audio = this.media.create(this.filePath); console.log("start recording..."); this.audio.startRecord(); console.log("recording is started..."); this.recordingMessage = "Device is recording..."; this.recording = true; } stopRecord() { if (this.audio) { this.audio.stopRecord(); console.log("Recording is stopped..."); // 停止后立刻释放资源,清空引用避免误操作 this.audio.release(); this.audio = null; } this.recordingMessage = "Recording is ended..."; let data = { filename: this.fileName }; this.audioList.push(data); localStorage.setItem("audiolist", JSON.stringify(this.audioList)); this.recording = false; } playAudio() { // 播放前先释放旧的播放资源 if (this.audio) { this.audio.release(); } if (this.platform.is('ios')) { this.filePath = this.file.dataDirectory + this.fileName; } else if (this.platform.is('android')) { this.filePath = this.file.dataDirectory + this.fileName; } this.audio = this.media.create(this.filePath); this.audio.play(); this.audio.setVolume(0.8); // 监听播放结束事件,自动释放资源 this.audio.onStatusUpdate.subscribe(status => { if (status === MediaStatus.COMPLETED) { this.audio.release(); this.audio = null; this.recordingMessage = "Playback finished"; } }); console.log("The device is playing audio..."); this.recordingMessage = "Device is playing audio..."; }
关键修复点说明
- 录音前清场:在
startRecord开头检查并释放旧的Media实例,确保音频设备处于可用状态 - 停止后彻底释放:
stopRecord里调用release()并清空this.audio引用,彻底释放资源 - 播放时的资源管理:播放前释放旧实例,还加了播放结束的监听,自动释放资源,避免长期占用
- 统一文件名逻辑:把文件名生成抽出来,减少重复代码,同时保证唯一性
额外小建议
- 可以加个错误监听:
this.audio.onError.subscribe(error => console.log('录音/播放错误:', error)),方便排查问题 - Android平台要注意权限配置,确保已经申请了
RECORD_AUDIO和WRITE_EXTERNAL_STORAGE权限(如果需要存到外部目录) - 测试时可以看生成的音频文件大小,如果第二次录音的文件只有几KB,说明还是资源释放没做好,数据没写进去
内容的提问来源于stack exchange,提问作者ilpostino
相关产品推荐
相关产品推荐

