android - 当我的 Cordova 应用程序进入后台时,如何在 InAppBrowser 上暂停 YouTube 视频?

标签 android cordova ionic-framework phonegap-plugins inappbrowser

我正在使用 Cordova 和 Ionic 框架开发 Android 应用程序。我正在使用以下代码通过 InAppBrowser 播放 YouTube 视频:

window.open('https://www.youtube.com/embed/rAiw2SXPS-4', '_self');

但是当我在播放视频时按下设备上的主页按钮时,视频没有暂停。由于这个问题,我的应用程序在提交到 Google Play 后被拒绝,原因如下:

Your submission has been rejected for enabling background playing of YouTube videos in violation of the YouTube API Terms of Service. If this submission was an update to an existing app, the version published prior to this update is still available in Google Play. Please modify your app and resubmit. Additional details have been sent to your account owner's email address.

我搜索了解决方案,但没有成功。有人可以帮忙吗?

最佳答案

我也在努力寻找在设备锁定时暂停(而不是停止)正在进行的视频的完整解决方案,但没有成功。最终我通过将几个部分组合在一起找到了自己的解决方案。

以下是实现设备锁定时 YouTube 播放器暂停的指令:

import { Directive, ElementRef, OnInit } from '@angular/core'
import { Platform } from 'ionic-angular'
import * as _ from 'lodash-es'

/* tslint:disable */
(function (apiInit) {
  let _registerYouTubeAPIIfNotAlready = function () {
    if (!window[ 'onYouTubeIframeAPIReady' ]) {
      window[ 'onYouTubeIframeAPIReady' ] = function () {
        apiInit.youTubeApiRegistered = true

        if ((typeof apiInit.callback !== "undefined") && _.isFunction(apiInit.callback)) {
          apiInit.callback()
        }
      }
    } else {
      console.error("trying to register YouTube API when it's already registered")
    }
  }

  apiInit.setupYouTubeApiOrDefault = function (callback) {
    if ((typeof callback === "undefined") || !_.isFunction(callback)) {
      _registerYouTubeAPIIfNotAlready()
      return
    }

    if(apiInit.youTubeApiRegistered){
      callback()
      return;
    }

    apiInit.callback = callback
    _registerYouTubeAPIIfNotAlready()
  }
}(window[ 'youTubeApiInit' ] = window[ 'youTubeApiInit' ] || {}))


@Directive({
  selector: "[preventYoutubePlayOnBackground]",
})
export class PreventYouTubePlayOnBackgroundDirective implements OnInit {
  public static youTubeIframeAPI = 'https://www.youtube.com/iframe_api'

  public static injectYouTubeIframeApi(): void {
    let youTubeCheckQuery = "script[src*='" + PreventYouTubePlayOnBackgroundDirective.youTubeIframeAPI + "']"

    if (!document.querySelector(youTubeCheckQuery)) {
      // from YouTube API documentation
      let tag = document.createElement('script')
      tag.src = PreventYouTubePlayOnBackgroundDirective.youTubeIframeAPI

      let firstScriptTag = document.getElementsByTagName('script')[ 0 ]
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag)
    }
  }

  public iframeId: string
  private youTubeIframeElm: any

  constructor(
    public elm: ElementRef,
    private platform: Platform,) {
    this.youTubeIframeElm = elm.nativeElement
    this.iframeId = this.youTubeIframeElm.getAttribute('id')
  }

  ngOnInit(): void {
    this.platform.ready().then(() => {
      PreventYouTubePlayOnBackgroundDirective.injectYouTubeIframeApi()

      window[ 'youTubeApiInit' ].setupYouTubeApiOrDefault(() => {
        this.setYouTubeApi()

        this.platform.pause.subscribe(() => {
          let player = new window[ 'YT' ].Player(this.iframeId) // TODO: add youtube API node module
          player.a.contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*')
        })
      })
    })
  }

  private setYouTubeApi(): void {
    let url = new URL(this.youTubeIframeElm.src)

    if (!url.searchParams.get("enablejsapi")) { // enabling youTube js api to be able to create player
      let prefix = (this.youTubeIframeElm.src.indexOf("?") === -1) ? "?" : "&"
      this.youTubeIframeElm.src += prefix + "enablejsapi=true"
    }
  }
}

嵌入式 YouTube 播放器的 HTML 将是:

<iframe id="onboarding-video"
                  width="400"
                  height="300"
                  [src]="videoUrl"
                  frameborder="0"
                  allowfullscreen
                  preventYoutubePlayOnBackground
                  iframe-id="onboarding-video">
</iframe>

注意:以上代码适用于 ionic 2+,但对于 ionic 1,您可以使用:

 (function() {
    // same kind of logic here as written in above constructor body

    $ionicPlatform.on('pause', function(event) {
      // pausing player here
    });
 }())

此外,您还需要创建 Angular 1 样式指令,而不是上面编写的 TypeScript 指令。

关于android - 当我的 Cordova 应用程序进入后台时,如何在 InAppBrowser 上暂停 YouTube 视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34835308/

相关文章:

android - 触摸焦点上自定义 ListView 的 TextView 项目的标记效果

ios - 隐藏 iOS 9 中 UIWebView 的快捷键盘栏

angularjs - Ui-sref 未在 ionic 框架中生成正确的 url

css - Ionic 全高列表

android - 在android中获取联系人非常慢

android textchangelistener 未被调用

Android:2个触摸位置之间的物理距离

android - Cordova Android 应用程序不接收来自服务器端的 FCM 通知

cordova - Meteor:在移动 Cordova 上等待热代码推送期间按住启动屏幕

javascript - 对象内未定义的值