YouTubeをバックグラウンド再生したいです。
「android-youtube-player」というAPIを使ってフォアグラウンドでYouTubeを再生することには成功しました。
しかし同APIではバックグラウンドで再生まではできませんでした。
(Serviceで再生するメソッドを発動させても何も起きなかった)
過去にteratailで同じ様な質問をしている投稿を見ました。
音楽と映像を切り離した再生はGoogleが禁止しているとの回答でした。
しかし通知に何を再生しているのか明示していれば問題ないとの話もあります。
また、GooglePlayには実際にバックグラウンドでYouTubeを再生しているGoogle非公式のアプリもあります。
ServiceでYouTubeをバックグラウンド再生するにはどのような方法があるでしょうか?
ご教授よろしくお願い致します。
再生できなかったServiceのコード
kotlin
class PlayService : Service() { inner class MyBinder : Binder() {} private val mBinder = MyBinder() override fun onBind(intent: Intent): IBinder? { return mBinder } private var handler = Handler() private var runnable = Runnable {} private var myApp = MyApplication.getInstance() // サービスの初期化時に実行する処理 override fun onCreate() { super.onCreate() } @RequiresApi(Build.VERSION_CODES.O) override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val setNotification: SetNotification? = myApp.setNotification val title = "再生中:" + myApp.videoTitle val loadVideoId = myApp.videoID val youTubePlayer = myApp.youtubePlayer val context = myApp.context!! // 通知を表示(動画タイトルを表示) if ((intent != null) && (setNotification != null)) { setNotification.createNotification(title) startForeground(111, setNotification.notificationBuilder.build()) } // 再生開始(再生できない) if (youTubePlayer != null) { loadVideoId?.let { youTubePlayer.loadVideo(it, 0f) } } // 1秒ごとに通知を更新開始 handler = Handler() runnable = object : Runnable { @RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun run() { // アプリがフォアグランドになったらサービスを終了 if(isForeground(context) == true){ stopSelf() return } handler.postDelayed(this, 1000) // 1秒間隔で更新 } } handler.post(runnable) return START_NOT_STICKY } // サービスの終了時に実行する処理 @RequiresApi(Build.VERSION_CODES.O) override fun onDestroy() { val youTubePlayer: YouTubePlayer? = myApp.youtubePlayer if (youTubePlayer != null) { youTubePlayer.pause() } // ハンドラーを停止 handler.removeCallbacks(runnable) } // アプリがフォアグランドかどうか調べる private fun isForeground(context: Context): Boolean { val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val runningProcesses = am.runningAppProcesses for (processInfo in runningProcesses) { for (activeProcess in processInfo.pkgList) { if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true } } } return false } }
まだ回答がついていません
会員登録して回答してみよう