この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
はじめに
こんにちは。モバイルアプリサービス部の平屋です。
本記事では、MusicKit JSを使用してWebページ上でApple Musicの曲を再生する実装を紹介します。
本記事は Apple からベータ版として公開されているドキュメントを情報源としています。 そのため、正式版と異なる情報になる可能性があります。ご留意の上、お読みください。
検証環境
- macOS High Sierra Version 10.13.4
- Google Chrome Version 66.0.3359.181
MusicKit JS
MusicKit JSはMusicKitの機能をWebページに追加するためのJavaScriptのライブラリです。
MusicKitの概要については以下の記事で紹介しています。
セットアップ
Developer Tokenを作成する
Developer Tokenを作成するには、以下の記事の「Music IDを作成する」から「Developer Tokenを作成する」までの作業を行います。
MusicKit JSのスクリプトをページに埋め込む
Scriptタグを追加してスクリプトを埋め込みます。
<script src=“https://js-cdn.music.apple.com/musickit/v1/musickit.js”></script>
初期設定を行う
musickitloaded
イベントを購読し、イベント発生時に MusicKit.configure
を呼んで初期設定を行います。developerToken
引数には、「Developer Tokenを作成する」で作成したトークンを指定します。
また MusicKit
のインスタンスを取得しておきます。
var musicKit;
document.addEventListener('musickitloaded', function() {
// MusicKit global is now defined
MusicKit.configure({
developerToken: 'xxxxxxxxxx',
app: {
name: 'My Cool MusicKit App',
build: '1'
}
});
musicKit = MusicKit.getInstance();
});
ログインを実装する
ボタンがクリックされたタイミングなどで authorize()
を呼び、ログイン処理を行います。
authorize()
を呼ぶと、Apple IDのログインページが別ウィンドウで開きます。処理が最後まで完了すると、コールバックが呼ばれます。
document.getElementById('authorize-button').addEventListener("click", function() {
musicKit.authorize().then(function() {
console.log('did authorize')
});
});
再生キューにアルバムを追加する
アルバムURLを使用して再生キューにアルバムを追加するには次のように実装します。
let url = 'https://itunes.apple.com/jp/album/love-is-dead/1348616259';
musicKit.setQueue({ url: url }).then(function(queue) {
// Queue is instantiated and set on music player.
console.log('did set queue by url')
});
また、アルバムIDを使用してアルバムを追加することもできます。
musicKit.setQueue({ album: '1348616259' }).then(function(queue) {
// Queue is instantiated and set on music player.
console.log('did set queue by id')
});
曲の再生/一時停止/停止を行う
曲の再生/一時停止/停止を行うには、MusicKit
の play()
pause()
stop()
を使用します。
musicKit.play()
console.log('did play')
musicKit.pause()
console.log('did pause')
musicKit.stop()
console.log('did stop')
さいごに
本記事では、MusicKit JSを使用してWebページ上でApple Musicの曲を再生する実装を紹介しました。
ドキュメントを大雑把に見てみましたが、iOS標準のミュージックアプリと同等の機能をWebページに組み込むことができそうです。今後、コンテンツ検索やユーザー固有のデータ取得なども試してみたいと思います。
これからMusicKit JSを触ってみようと思っている方の参考になれば幸いです。
参考資料
- MusicKit JS | Apple Developer Documentation
- Accessing MusicKit Features Using JavaScript | Apple Developer Documentation
- MusicKit - MusicKit JS | Apple Developer Documentation
関連セッション
以下のセッションでMusicKit JSの紹介があるようです。
- MusicKit on the Web - WWDC 2018 - Videos - Apple Developer
- 6/8 10:00 AM to 10:40 AM(PDT)
MusicKit has enabled the creation of new, compelling, and engaging Apple Music powered app experiences. With the introduction of MusicKit on the web, as a developer, you can now bring Apple Music powered experiences to the web. Learn how to use declarative markup or javascript to enable Apple Music on your website.