jQuery + SoundCloudでシンプルなプレイリストを作成する
いろいろ至らないところもあるかもしれません。なんかおかしいところもあるかもしれません。でもとりあえず上手くいったから。おかしい点があれば、ご意見いただけると嬉しいです。
やりたいこと
- SoundCloudのplaylistから自動的に曲目を収集する。
- 曲タイトルをクリックするとその曲が再生。もう一度押すと停止。
- 再生が終わると次のトラックを再生する
- コントローラーはいらない
- 再生中に他の曲をクリックしたら、今まで再生中だった曲は停止される。
できあがったもの
参考にしたサイト
A simple html5 audio player for jQuery
http://github.com/yuanhao/Simple-Player
http://github.com/yuanhao/Simple-Player
video要素、audio要素をJavaScriptから操作する
http://www.htmq.com/video/
http://www.htmq.com/video/
PHP
$consumer_key = *****; $playlist_id = *****; $url = 'http://api.soundcloud.com/playlists/' . $playlist_id . '.json?client_id=' . $consumer_key; $json_string = file_get_contents($url); $obj = json_decode($json_string); $sounds = $obj->tracks; echo '<img src="' . htmlspecialchars($obj->artwork_url) . '" alt="' . htmlspecialchars($obj->title) . '">'; echo '<h1><a href="' . htmlspecialchars($obj->permalink_url) . '">' . htmlspecialchars($obj->title) . '</a></h1>'; echo '<p>by <a href="' . htmlspecialchars($obj->user->permalink_url) . '" target="_blank">' . htmlspecialchars($obj->user->username) . '</a></p>'; echo '<ol class="audio-list">'; foreach ($sounds as $sound) : $mp3_url = $sound->stream_url . '?consumer_key=' . $consumer_key; $song_output = '<li>' . htmlspecialchars($sound->title) $song_output .= '<span></span>'; $song_output .= '<audio>'; $song_output .= '<source src="' . htmlspecialchars($mp3_url) . '" type="audio/mp3" />'; $song_output .= '<source src="' . htmlspecialchars($mp3_url) . '" type="audio/ogg" />'; $song_output .= '</audio>'; $song_output .= '</li>'; echo $song_output; endforeach; echo '</ol>';
※ なぜoggも読み込むのかと思われるかもしれませんが、これをしないとAndroidでは再生されませんでした。
下記のような記事もありました。
Androidで音声扱うときはoggにしとくのが良いっぽい
http://d.hatena.ne.jp/itog/20100418/1271593207
http://d.hatena.ne.jp/itog/20100418/1271593207
jQuery
$(function () { $.fn.playlist = function() { function stopAudio(audio) { $('.play').removeClass('play'); audio.pause(); } this.find('li').each(function() { var audio = $(this).find('audio').get(0), button = $(this).find('span'); //再生時の処理 $(audio).bind('play',function() { $(button).addClass('play'); }).bind('pause', function() { stopAudio(audio); }); $(audio).bind('ended', function() { var nextTrack = $(audio).parent().next('li').find('audio').get(0); stopAudio(audio); if (nextTrack) { nextTrack.play(); } }); //ボタンをクリックしたら $(this).on('click', function() { if (audio.paused) { if ($('.play').length) { playing = $('.play').parents('li').find('audio').get(0); stopAudio(playing); } audio.play(); } else { audio.pause(); } }); }); }; $(".audio-list").playlist(); });
li要素の中のspan要素にあらかじめ停止ボタン画像を設定しておきます。
曲名をクリックすると「play」というクラス名が付与されますので、ここに再生ボタン画像を設定しておきます。