1/* 2 * Copyright (c) 2022 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 */ 15import mediaLibrary from '@ohos.multimedia.mediaLibrary' 16import Logger from '../model/Logger' 17 18export default class MediaUtils { 19 private tag: string = 'MediaUtils' 20 private mediaList: Array<mediaLibrary.FileAsset> = [] 21 private mediaLib: mediaLibrary.MediaLibrary = undefined 22 23 constructor(context: any) { 24 this.mediaLib = mediaLibrary.getMediaLibrary(context) 25 } 26 27 async queryFile(id) { 28 Logger.info(this.tag, `queryFile,id = ${id}`) 29 let fileKeyObj = mediaLibrary.FileKey 30 if (!id) { 31 return 32 } 33 let args = id.toString() 34 let fetchOp = { 35 selections: `${fileKeyObj.ID}=?`, 36 selectionArgs: [args], 37 } 38 const fetchFileResult = await this.mediaLib.getFileAssets(fetchOp) 39 Logger.info(this.tag, `fetchFileResult.getCount() = ${fetchFileResult.getCount()}`) 40 const fileAsset = await fetchFileResult.getAllObject() 41 return fileAsset[0] 42 43 } 44 45 getMediaList() { 46 return this.mediaList 47 } 48 49 async getFdPath(fileAsset: any) { 50 let fd = await fileAsset.open('Rw') 51 Logger.info(this.tag, `fd = ${fd}`) 52 return fd 53 } 54 55 async getFileAssetsFromType(mediaType: number) { 56 Logger.info(this.tag, `getFileAssetsFromType,mediaType = ${mediaType}`) 57 let fileKeyObj = mediaLibrary.FileKey 58 let fetchOp = { 59 selections: `${fileKeyObj.MEDIA_TYPE}=?`, 60 selectionArgs: [`${mediaType}`], 61 } 62 let fetchFileResult = await this.mediaLib.getFileAssets(fetchOp) 63 Logger.info(this.tag, `getFileAssetsFromType,fetchFileResult.count = ${fetchFileResult.getCount()}`) 64 if (fetchFileResult.getCount() > 0) { 65 this.mediaList = await fetchFileResult.getAllObject() 66 } 67 return this.mediaList 68 } 69 70 deleteFile(media: any) { 71 let uri = media.uri 72 Logger.info(this.tag, `deleteFile,uri = ${uri}`) 73 return this.mediaLib.deleteAsset(uri) 74 } 75 76 onDateChange(callback: () => void) { 77 this.mediaLib.on('videoChange', () => { 78 Logger.info(this.tag, 'videoChange called') 79 callback() 80 }) 81 } 82 83 offDateChange() { 84 this.mediaLib.off('videoChange') 85 } 86}