【WordPress】howler.jsでオーディオプレイヤーを実装したよ

本ブログはアフィリエイト広告を利用しています

WEB / アプリ
WEB / アプリ
この記事は約18分で読めます。

とっちゃん@nyanco! です。

今回はhowler.jsライブラリを使ってWordPressの投稿記事にセットしたMP3ファイルを再生するオーディオプレイヤーを実装したのでその手順を画像付きで分かりやすく解説するよというお話です。

肉玉にゃんこ

howler.jsとはMP3などの音源ファイルの再生・停止などを簡単に実装できるJavascriptのオーディオライブラリですにゃ〜
無料で利用することができますにゃ〜

WordPressのfunctions.phpを含むテーマファイルを編集します。記述を誤ると、最悪Webサイトが表示されなくなるなどのリスクがあるので、何か不具合が起こっても復帰できるように作業前に必ずプラグインなどでバックアップするようにしてください。くれぐれも自己責任でお願いいたします。

スポンサーリンク

本記事でできること

  • 投稿一覧ページで各投稿でセットしたmp3ファイルの再生
  • 再生/停止ボタン、再生時間表示、シークバー、ボリュームコントロールの実装

完成イメージはこちら(赤枠部分)です。

▼ちなみに実装した筆者のWebサイトはこちら(随時更新しているので、デザインが変わっている可能性があります)。

nyanco! MUSIC
他にはない完全オリジナルBGMが無料でダウンロードできる!商用使用OK😻

事前準備

  • JQuery読み込み(WordPressであればデフォルトで組み込まれているので特に何もしなくてOK)
  • 「URL」を入力できるカスタムフィールドaudio_urlという名前で作成

カスタムフィールドはACF(Advanced Custom Fields)などのプラグインで作成、もしくはfunction.phpに記述して作成します。

肉玉にゃんこ

カスタムフィールド名は任意でもOKですが、本記事ではaudio_urlで進めていきますにゃ〜

howler.jsでオーディオプレイヤーを実装する手順

Step1. howler.jsをダウンロード

▼まずはhowler.js公式サイトにアクセスして「Download」をクリックします。

Github(ギットハブ)サイトに遷移するので「Code」をクリック→「Download ZIP」をクリックします。

Githubとは、プログラムなどのソースコードをオンラインで共有・管理するサービスです。2,700万人以上のユーザーが利用しています。

「howler.js-master.zip」という圧縮ファイルがダウンロードされるので解凍します。生成されたhowler.js-masterフォルダの中にあるdistフォルダ内の「howler.min.js」というファイルを確認できればOKです。

肉玉にゃんこ

いっぱいファイルがあるけど今回使うのはこのファイルだけですにゃ〜!

Step2. howler.min.jsをjsフォルダに格納

▼続いてローカルに「js」というフォルダを作成し、Step1. で確認した「howler.min.js」を格納します。

肉玉にゃんこ

「howler.min.js」はコピーしても移動でもどちらでもOKですにゃ〜!

Step3. audio-player.jsを作成

▼続いて同じフォルダ内にもう一つjsファイルを作成します。テキストファイルを新規作成しても良いですが、Step2. の「howler.min.js」を複製してリネームするのが手っ取り早いです。ファイル名は任意でもOKですが、本記事ではaudio-player.jsとします。

audio-player.jsをテキストエディタなどで開き、(「howler.min.js」を複製した場合は先に全選択→削除しておく)下記コードをコピーペーストして上書き保存します。

jQuery(document).ready(function($) {
    var playingSound = null; // 再生中の Howl オブジェクトを保持

    // AudioContextの初期化(iPhoneでの再生安定化)
    document.addEventListener('click', function() {
        if (Howler.ctx.state !== 'running') {
            Howler.ctx.resume().then(() => {
                console.log('AudioContext resumed');
            }).catch(err => {
                console.error('Failed to resume AudioContext:', err);
            });
        }
    }, { once: true });

    $('.audio-player').each(function() {
        var $player = $(this);
        var url = $player.attr('data-audio_url');

        if (url) {
            var sound = new Howl({
                src: [url],
                html5: true, // iPhoneでの安定性向上
                format: ['mp3', 'aac'], // 複数フォーマット対応
                onload: function() {
                    $player.find('.duration').text(formatTime(sound.duration()));
                    $player.find('.seek-bar').attr('max', sound.duration());
                },
                onplay: function() {
                    // 他の再生を停止
                    if (playingSound && playingSound !== sound) {
                        playingSound.pause();
                    }
                    playingSound = sound;

                    $player.find('.play-button i').removeClass('fa-play').addClass('fa-pause');

                    // シークバーと時間の更新
                    updateSeekBar();
                },
                onpause: function() {
                    $player.find('.play-button i').removeClass('fa-pause').addClass('fa-play');
                    if (playingSound === sound) {
                        playingSound = null;
                    }
                },
                onend: function() {
                    resetPlayer();
                }
            });

            // 再生/一時停止ボタン
            $player.find('.play-button').on('click', function(event) {
                event.preventDefault();
                if (sound.playing()) {
                    sound.pause();
                } else {
                    sound.play();
                }
            });

            // シークバー変更
            $player.find('.seek-bar').on('change', function() {
                sound.seek($(this).val());
            });

            // 音量調整
            $player.find('.volume-slider').on('input', function() {
                sound.volume($(this).val());
            });

            // バックグラウンド復帰時に再生を再開
            document.addEventListener("visibilitychange", function() {
                if (!document.hidden && playingSound === sound) {
                    sound.play();
                }
            });

            // シークバーの更新関数
            function updateSeekBar() {
                var interval = setInterval(function() {
                    if (!sound.playing()) {
                        clearInterval(interval);
                        return;
                    }
                    $player.find('.current-time').text(formatTime(sound.seek()));
                    $player.find('.seek-bar').val(sound.seek());
                }, 500); // 更新頻度を調整
                sound.on('pause', () => clearInterval(interval));
                sound.on('end', () => clearInterval(interval));
            }

            // プレイヤーリセット
            function resetPlayer() {
                $player.find('.play-button i').removeClass('fa-pause').addClass('fa-play');
                $player.find('.current-time').text('0:00');
                $player.find('.seek-bar').val(0);
                if (playingSound === sound) {
                    playingSound = null;
                }
            }

            // 時間フォーマット関数
            function formatTime(secs) {
                var minutes = Math.floor(secs / 60) || 0;
                var seconds = Math.floor(secs - minutes * 60) || 0;
                return minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
            }
        }
    });
});
肉玉にゃんこ

このaudio-player.jsがオーディオプレイヤーのキモとなってきますにゃ〜

こだわったポイントは以下の通り。

  • ページ読み込み時に再生時間を自動読み込み
  • 再生中でもシークバー移動可能
  • 同時再生は不可(最後に再生した音源が優先される)

Step4. jsフォルダをアップロード

FTPソフトなどでWordPressのテーマファイルフォルダの第一階層jsフォルダごとアップロードします。

肉玉にゃんこ

基本は子テーマにアップロードですにゃ〜
Cocoonなら「cocoon-child」フォルダになりますにゃ〜

Step5. functions.phpを編集

▼続いてWordPressテーマの「functions.php」ファイルを開き、以下のコードを追記します。

function my_theme_enqueue_scripts() {
    wp_enqueue_script( 'howler', get_stylesheet_directory_uri() . '/js/howler.min.js', array(), '2.2.4', true );
    wp_enqueue_script( 'audio-player', get_stylesheet_directory_uri() . '/js/audio-player.js', array( 'jquery', 'howler' ), '2.2.4', true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
肉玉にゃんこ

Step2.3.で作成したjsファイルをここで読み込む形ですにゃ〜
ちなみに「’2.2.4’」とは「howler.min.js」を開くと1行目で確認できるバージョン数なので異なる場合は変更する必要がありますにゃ〜

ちなみに「get_stylesheet_directory_uri()」は有効化している「テーマ」のテーマディレクトリURLを取得する関数です。似たものとして「get_template_directory_uri()」は有効化しているテーマの「親テーマ」のテーマディレクトリURLを取得する関数となります。
get_stylesheet_directory_uri():有効化している「テーマ」のテーマディレクトリURLを取得 ※子テーマを有効化していたら子テーマURLを取得
get_template_directory_uri():有効化しているテーマの「親テーマ」のテーマディレクトリURLを取得 ※子テーマを有効化していても親テーマURLを取得

Step6. テンプレートファイルを編集

続いてWordPressのエントリーカードを定義しているテンプレートファイルを編集していきます。

肉玉にゃんこ

Cocoonでいうとtmpフォルダ内にある「entry-card.php」となりますにゃ〜

オーディオプレイヤーを設置したい箇所に以下のコードをコピーペーストします。

		<div class="audio-player" data-audio_url="<?php echo esc_url( get_post_meta( get_the_ID(), 'audio_url', true ) ); ?>">
			<div><a class="play-button"><i class="fas fa-play"></i></a></div>
			<input type="range" class="seek-bar" value="0" min="0" max="100">
			<span class="current-time">0:00</span> / <span class="duration">0:00</span>
			<div class="volume-control">
				<i class="fas fa-volume-up"></i>
				<input type="range" class="volume-slider" value="0.5" min="0" max="1" step="0.1">
			</div>
		</div>

ポイントは1行目の「audio_url」です。こちらはURLのカスタムフィールド名と一致させておく必要があります。
また、1行目の「data-audio_url」はaudio-player.jsの6行目のそれと一致する必要があります。

▼参考までに、オーディオプレイヤー周りのCSSは以下となります。

/* オーディオプレイヤーCSS */
.audio-player {
    display: flex;
    align-items: center;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
    margin-bottom: 10px;
}
.play-button {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background-color: #2CA3B6; /* 色を変更 */
    color: #fff;
    border: none;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 0.4em;
    cursor: pointer;
    margin-right: 10px;
	text-decoration:none;
	transition : 1s;
}
.play-button:hover {
    opacity:0.6;
	color:#fff;
}
.play-button i {
    font-size: 1.5em;
}
.seek-bar {
    flex-grow: 1;
    -webkit-appearance: none;
    height: 5px;
    background: #ddd;
    border-radius: 5px;
    outline: none;
    margin-right: 10px;
}
.seek-bar::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 15px;
    height: 15px;
    background: #2CA3B6; /* 色を変更 */
    border-radius: 50%;
    cursor: pointer;
}
.seek-bar::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #2CA3B6; /* 色を変更 */
    border-radius: 50%;
    cursor: pointer;
}
.current-time, .duration {
    width: 40px;
    text-align: center;
    font-size: 0.8em;
    color: #666;
}
.volume-control {
    display: flex;
    align-items: center;
    margin-left: 10px;
}
.volume-control i {
    margin-right: 5px;
}
.volume-slider {
    width: 60px;
    -webkit-appearance: none;
    height: 5px;
    background: #ddd;
    border-radius: 5px;
    outline: none;
}
.volume-slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 15px;
    height: 15px;
    background: #2CA3B6; /* 色を変更 */
    border-radius: 50%;
    cursor: pointer;
}
.volume-slider::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #2CA3B6; /* 色を変更 */
    border-radius: 50%;
    cursor: pointer;
}
/* /オーディオプレイヤーCSS */

▼見た目はこんな感じ(赤枠部分)になりますが、CSSが触れる方はお好みでカスタマイズ可能です!

Step7. MP3データを用意

続いて肝心のMP3データをセットしていきます。

▼まずはMP3データをテーマフォルダの第一階層にアップロードしますが、直にMP3ファイルをアップロードすると第一階層がごちゃごちゃになるので本記事では「data」というフォルダを作成してアップロードしました(ファイル名はURLの一部となるので日本語は非推奨!)。

ちなみにアップロード先はテーマフォルダでもWordPressフォルダ直下でもOKです。WordPress直下の方が以下のようにURLが短くなるのでお好みでどうぞ。

  • テーマフォルダ:https://xxx.jp/wp-content/themes/cocoon-child/data/music.mp3
  • WordPress直下:https://xxx.jp/data/music.mp3

▼続いてWordPressの投稿画面にタイトルなどの情報とカスタムフィールド「audio_url」に先程アップロードしたMP3のファイル名を含めたURLを入力して公開します。

Step8. オーディオの再生を確認

最後にブラウザでwebサイトを閲覧し、オーディオが正常に再生されるかを確認して問題なければ完了です!

肉玉にゃんこ

お疲れ様でしたにゃ〜!

おわりに

本記事がどなたかの参考になれば幸いです。

今回は以上となります。
最後まで読んでいただきましてありがとうございました!
それではまた〜✧٩(ˊωˋ*)و✧

コメント