1/* 2 * Copyright (c) 2023 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 mediaLibrary from '@ohos.multimedia.mediaLibrary' 18import Logger from '../model/Logger' 19 20const TAG: string = '[Recorder.AudioModel]' 21 22export class AudioModel { 23 private audioPlayer = undefined; 24 private playFile: mediaLibrary.FileAsset = undefined 25 private dataLoad: boolean = false 26 27 initAudioPlayer(playSrc: mediaLibrary.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 console.info(`${TAG}set onFinish`) 62 this.audioPlayer.on('finish', () => { 63 Logger.info(TAG, `audioPlayer finish called`) 64 this.audioPlayer.seek(0) 65 callback() 66 }); 67 } 68 69 play(callback) { 70 if (typeof (this.audioPlayer) != `undefined`) { 71 this.audioPlayer.on('play', () => { 72 Logger.info(TAG, `audioPlayer play called`) 73 callback() 74 }) 75 if (this.dataLoad) { 76 this.audioPlayer.play() 77 } else { 78 this.audioPlayer.on('dataLoad', () => { 79 Logger.info(TAG, `case dataLoad called`) 80 this.dataLoad = true 81 this.audioPlayer.play() 82 }) 83 } 84 } 85 } 86 87 pause(callback) { 88 if (typeof (this.audioPlayer) != `undefined`) { 89 this.audioPlayer.on('pause', () => { 90 Logger.info(TAG, `case pause called`) 91 callback() 92 }) 93 this.audioPlayer.pause() 94 } 95 } 96 97 finish() { 98 if (typeof (this.audioPlayer) != `undefined`) { 99 this.audioPlayer.stop() 100 } 101 } 102}