1/* 2 * Copyright (c) 2023-2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import media from '@ohos.multimedia.media'; 17import userFileManager from '@ohos.filemanagement.userFileManager'; 18import Logger from '../model/Logger'; 19 20const TAG: string = '[Recorder.AudioModel]'; 21 22export class AudioModel { 23 private audioPlayer = undefined; 24 private playFile: userFileManager.FileAsset = undefined; 25 private dataLoad: boolean = false; 26 27 initAudioPlayer(playSrc: userFileManager.FileAsset, isPlay) { 28 this.playFile = playSrc 29 this.dataLoad = false 30 this.release() 31 this.audioPlayer = media.createAudioPlayer() 32 this.audioPlayer.on('dataLoad', () => { 33 Logger.info(TAG, `case dataLoad called`) 34 this.dataLoad = true 35 }) 36 this.audioPlayer.on('stop', () => { 37 Logger.info(TAG, `audioPlayer stop called`) 38 this.audioPlayer.release() 39 this.audioPlayer = undefined 40 }) 41 this.audioPlayer.on('error', () => { 42 Logger.info(TAG, `audioPlayer error called`) 43 }) 44 this.audioPlayer.reset() 45 let fdPath = playSrc.open('r') 46 fdPath.then(fdNumber => { 47 this.audioPlayer.src = `fd://${fdNumber}` 48 Logger.info(TAG, `create audioPlayer success`) 49 }) 50 } 51 52 release() { 53 if (typeof (this.audioPlayer) != `undefined`) { 54 Logger.info(TAG, `audioPlayer release`) 55 this.audioPlayer.release() 56 this.audioPlayer = undefined 57 } 58 } 59 60 onFinish(callback) { 61 Logger.info(TAG, `set onFinish`); 62 this.audioPlayer.on('finish', () => { 63 Logger.info(TAG, `audioPlayer finish called`); 64 this.audioPlayer.seek(0); 65 this.finish(); 66 callback(); 67 }); 68 } 69 70 play(callback) { 71 if (typeof (this.audioPlayer) != `undefined`) { 72 this.audioPlayer.on('play', () => { 73 Logger.info(TAG, `audioPlayer play called`) 74 callback() 75 }) 76 if (this.dataLoad) { 77 this.audioPlayer.play() 78 } else { 79 this.audioPlayer.on('dataLoad', () => { 80 Logger.info(TAG, `case dataLoad called`) 81 this.dataLoad = true 82 this.audioPlayer.play() 83 }) 84 } 85 } 86 } 87 88 pause(callback) { 89 if (typeof (this.audioPlayer) != `undefined`) { 90 this.audioPlayer.on('pause', () => { 91 Logger.info(TAG, `case pause called`) 92 callback() 93 }) 94 this.audioPlayer.pause() 95 } 96 } 97 98 finish() { 99 if (typeof (this.audioPlayer) != `undefined`) { 100 this.audioPlayer.pause(); 101 } 102 } 103}