当我的Cordova应用程序进入后台时,如何在InAppBrowser上暂停YouTube视频? [英] How to pause YouTube video on InAppBrowser when my Cordova app goes to background?

查看:272
本文介绍了当我的Cordova应用程序进入后台时,如何在InAppBrowser上暂停YouTube视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing an Android app using Cordova and Ionic framework. I am playing a YouTube video with InAppBrowser using the code below:

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

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

But when I press the home button on the device while playing the video, the video is not paused. Due to this issue, my app is rejected after submitting to Google Play with the reason below:


您的提交已被拒绝以启用后台播放YouTube视频违反YouTube API服务条款。如果此提交是对现有应用的更新,则此更新之前发布的版本仍可在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.

我搜索了一个解决方案,但没有运气。任何人都可以帮忙吗?

I searched for a solution but have no luck. Can anybody help?

推荐答案

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

I was also struggling to find complete solution to pause(not stop) ongoing video(s) when device locks, but with no success. Eventually I found solution myself by combining several parts together.

这是完成设备锁定时YouTube播放器暂停的指令:

Here is the directive that accomplishes YouTube player pause on device lock:

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将为:

HTML for embedded YouTube player will be:

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

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

Note: above code is for ionic 2+, however for ionic 1 you can use:

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

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

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

Also you will need to create Angular 1 style directive instead of TypeScript one written above.

这篇关于当我的Cordova应用程序进入后台时,如何在InAppBrowser上暂停YouTube视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆