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 16 #ifndef SOUNDPOOL_CALLBACK_NAPI_H 17 #define SOUNDPOOL_CALLBACK_NAPI_H 18 19 #include "napi/native_api.h" 20 #include "napi/native_node_api.h" 21 #include "common_napi.h" 22 #include "media_errors.h" 23 #include "media_log.h" 24 #include "isoundpool.h" 25 26 namespace OHOS { 27 namespace Media { 28 namespace SoundPoolEvent { 29 const std::string EVENT_LOAD_COMPLETED = "loadComplete"; 30 const std::string EVENT_PLAY_FINISHED = "playFinished"; 31 const std::string EVENT_PLAY_FINISHED_WITH_STREAM_ID = "playFinishedWithStreamId"; 32 const std::string EVENT_ERROR = "error"; 33 } 34 35 class SoundPoolCallBackNapi : public ISoundPoolCallback { 36 public: 37 explicit SoundPoolCallBackNapi(napi_env env); 38 ~SoundPoolCallBackNapi() = default; 39 void SaveCallbackReference(const std::string &name, std::weak_ptr<AutoRef> ref); 40 void CancelCallbackReference(const std::string &name); 41 void ClearCallbackReference(); 42 void SendErrorCallback(int32_t errCode, const std::string &msg); 43 void SendLoadCompletedCallback(int32_t soundId); 44 void SendPlayCompletedCallback(int32_t streamID); 45 46 protected: 47 void OnLoadCompleted(int32_t soundId) override; 48 void OnPlayFinished(int32_t streamID) override; 49 void OnError(int32_t errorCode) override; 50 51 private: 52 struct SoundPoolJsCallBack { 53 void RunJsErrorCallBackTask(int status, SoundPoolJsCallBack *event); 54 void RunJsloadCompletedCallBackTask(int status, SoundPoolJsCallBack *event); 55 void RunJsplayCompletedCallBackTask(int status, SoundPoolJsCallBack *event); 56 57 std::weak_ptr<AutoRef> autoRef; 58 std::string callbackName = "unknown"; 59 std::string errorMsg = "unknown"; 60 int32_t errorCode = MSERR_EXT_UNKNOWN; 61 int32_t reason = 1; 62 int32_t loadSoundId = 0; 63 int32_t playFinishedStreamID = 0; 64 }; 65 void OnJsErrorCallBack(SoundPoolJsCallBack *jsCb) const; 66 void OnJsloadCompletedCallBack(SoundPoolJsCallBack *jsCb) const; 67 void OnJsplayCompletedCallBack(SoundPoolJsCallBack *jsCb) const; 68 napi_env env_ = nullptr; 69 std::mutex mutex_; 70 std::map<std::string, std::weak_ptr<AutoRef>> refMap_; 71 }; 72 } // namespace Media 73 } // namespace OHOS 74 #endif // SOUNDPOOL_CALLBACK_NAPI_H 75