AdManager.ts 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { sys } from "cc";
  2. import { oops } from "../../../../extensions/oops-plugin-framework/assets/core/Oops";
  3. // AdManager.ts
  4. export class AdManager {
  5. private static instance: AdManager;
  6. // 微信和抖音的激励视频广告对象
  7. private rewardVideoAd: any = null;
  8. // 广告单元ID,请替换为你的实际广告单元ID
  9. private adUnitId: string = 'adunit-d8e3c2b4bcfdc32e';
  10. private dyAdUnitId:string = 'adunit-d8e3c2b4bcfdc32e'
  11. private constructor() {}
  12. // 获取AdManager的单例对象
  13. public static getInstance(): AdManager {
  14. if (!AdManager.instance) {
  15. AdManager.instance = new AdManager();
  16. }
  17. return AdManager.instance;
  18. }
  19. // 初始化激励视频广告
  20. public initRewardVideoAd() {
  21. if (sys.platform === sys.Platform.WECHAT_GAME) {
  22. // 微信小游戏环境
  23. this.rewardVideoAd = wx.createRewardedVideoAd({ adUnitId: this.adUnitId });
  24. this.rewardVideoAd.onError(err => {
  25. console.error('RewardedVideoAd Error: ', err);
  26. });
  27. } else if (sys.platform === sys.Platform.BYTEDANCE_MINI_GAME) {
  28. // 抖音小游戏环境
  29. this.rewardVideoAd = tt.createRewardedVideoAd({ adUnitId: this.dyAdUnitId });
  30. this.rewardVideoAd.onError(err => {
  31. console.error('RewardedVideoAd Error: ', err);
  32. });
  33. }
  34. }
  35. // 显示激励视频广告
  36. public showRewardVideoAd(successCallback?: () => void, failCallback?: (err: any) => void) {
  37. if (this.rewardVideoAd) {
  38. this.rewardVideoAd.show().then(() => {
  39. console.log('Rewarded video ad displayed!');
  40. // successCallback && successCallback();
  41. }).catch(err => {
  42. console.error('Failed to display rewarded video ad:', err);
  43. this.rewardVideoAd.load().then(() => this.rewardVideoAd.show());
  44. failCallback && failCallback(err);
  45. oops.audio.resumeAll()
  46. });
  47. // 监听广告关闭事件
  48. this.rewardVideoAd.onClose((res: any) => {
  49. // 用户观看完整广告
  50. if (res && res.isEnded) {
  51. console.log('Rewarded video ad watched till the end');
  52. successCallback && successCallback();
  53. oops.audio.resumeAll()
  54. } else {
  55. // 用户提前关闭广告
  56. console.log('Rewarded video ad was closed before completion');
  57. failCallback && failCallback(new Error('Ad was closed before completion'));
  58. oops.audio.resumeAll()
  59. }
  60. });
  61. } else {
  62. console.error('Reward video ad is not initialized.');
  63. failCallback && failCallback(new Error('Reward video ad is not initialized'));
  64. // successCallback && successCallback();
  65. oops.audio.resumeAll()
  66. }
  67. }
  68. }