4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

YouTube が再生中なら iTunes を停止 (逆も) (OS X 限定)

Last updated at Posted at 2015-04-26

最近 YouTube で動画を見始めたら iTunes を止めたい!
と思ったので、 JXA でチャレンジしてみた。

もちろん逆に、 YouTube で再生中でない場合は iTunes を再生し始める。

autotunes
# !/usr/bin/env osascript -l JavaScript

var executeJS = {
    // http://qiita.com/zakuroishikuro/items/194223d63b0f95ab7a63
    'Google Chrome': function (app, tab, fnStr) {
        return app.execute(tab, {'javascript': fnStr});
    },
    'Safari': function (app, tab, fn) {
        return app.doJavaScript(fnStr, {'in': tab});
    }
};

function main () {
    var iTunes = Application('iTunes');
    if (someAppYouTubePlaying()) {
        iTunes.stop();
    } else {
        iTunes.play();
    }
}

main();

function someAppYouTubePlaying() {
    var browserNames = Object.keys(executeJS);
    return selectActiveApps(browserNames).some(function (app) {
        return app.windows().some(function (window) {
            return window.tabs().some(function (tab) {
                return youtubePlaying(app, window, tab);
            });
        });
    });
}

function selectActiveApps(appNames) {
    var se = Application('System Events');
    return se.processes().reduce(function (actives, app) {
        var appName = app.name();
        if (appNames.indexOf(appName) > -1) {
            actives.push(Application(appName));
        }
        return actives;
    }, []);
}

function youtubePlaying(app, window, tab) {
    var js = '(' + isYoutubePlaying.toString() + ')();';
    return executeJS[app.name()](app, tab, js); 
}

function isYoutubePlaying() {
    // This function will be running on browser (client side JS).
    // https://developers.google.com/youtube/js_api_reference
    const STOP = 0;
    const PAUSE = 2;
    if (!String(window.location).match(/https?:\/\/www\.youtube\.com/)) {
        return false;
    }
    var player = document.getElementById('movie_player');
    if (!player) {
        return false;
    }
    if ([STOP, PAUSE].indexOf(player.getPlayerState()) > -1) {
        return false;
    }
    return true;
}

使い方

実行権限をつけて実行するだけ。

$ chmod +x ./autotunes
$ ./autotunes

自分は、これをさらに定期的に実行してくれるように、パスを通して
こんな感じの Bash スクリプトを書いて、これを実行している。
1 秒おき。

# !/usr/bin/env bash
set -euo pipefail

while sleep 1
do
    autotunes
done

Safari と Google Chrome での差異の吸収は↓の記事を参考にさせていただいた。
JXAでSafari, Chrome, Firefoxを操作する際の違い

工夫次第で他のブラウザや他の動画再生サイト・他の音声プレイヤーでもできる(たぶん)……!

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?