> For the complete documentation index, see [llms.txt](https://ja.docs.monaca.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ja.docs.monaca.io/sampleapp/tips/media.md).

# 音楽の再生方法

Monaca で音楽を再生する方法について説明します。

HTMLのAudioオブジェクトを利用することで、音声ファイルを操作することができます。

下のプロジェクトではアプリ内(wwwディレクト配下)に保存した音声ファイルと外部サーバーに保存してある音声ファイルを再生しています。

## 画面の作成

音声ファイルを操作するためのページを作成します。

* 音声ファイルの選択
* 音声の再生・一時停止・停止ボタン
* 音声の再生位置の表示

下記のプロジェクトでは、プロジェクトのwwwディレクト配下に保存した`song1.mp3` と 外部サイトにあるmp3ファイルをURLで指定しています。

```markup
<body style="text-align: center">
    <h1>Playing Sound</h1>
    <select id="songSelect">
        <option value="song1.mp3">Song 1</option>
        <option value="https://www.learningcontainer.com/wp-content/uploads/2020/02/Kalimba.mp3">Song 2</option>
    </select>
    <button onclick="playSound()">Play</button>
    <button onclick="pauseSound()">Pause</button>
    <button onclick="stopSound()">Stop</button>
    <p id="audio_position"></p>
</body>
```

## 音声再生の準備

ページが読み込まれたとき(`window.onload`)に音声再生の準備をします。

まず、音声ファイルとタイマーを管理するための変数を宣言します。次に、音声ファイルを再生するためのAudioオブジェクトを作成し、`audioElement`に代入します。さらに、音声が再生されたとき、一時停止したとき、再生が終了したときに呼び出される関数を設定します。

```javascript
var audioElement;
var srcFile = "sample.mp3";
var timer;

window.onload = function() {
    audioElement = new Audio(srcFile);
    audioElement.addEventListener('play', updateAudioPosition, false);
    audioElement.addEventListener('pause', stopUpdatingAudioPosition, false);
    audioElement.addEventListener('ended', stopUpdatingAudioPosition, false);
};
```

## 音声の操作

次に3つの関数、音声の再生、一時停止、停止を作成します。

* `playSound`関数では、選択された曲を再生します。
* `pauseSound`関数では、音声の再生を一時停止します。
* `stopSound`関数では、音声の再生を停止し、再生位置を初めに戻します。

```javascript
function playSound() {
    const selectedSong = document.getElementById('songSelect').value;
    const selectedFilename = getFilenameFromPathOrURL(selectedSong);
    const audioFilename = getFilenameFromPathOrURL(audioElement.src);

    if (audioFilename != selectedFilename) {  
        audioElement.src = selectedSong;
    }
}

function pauseSound() {
    audioElement.pause();
}

function stopSound() {
    audioElement.pause();
    audioElement.currentTime = 0;
    setAudioPosition(audioElement.currentTime);
}

function getFilenameFromPathOrURL(input) {
    // URLの場合として解析を試みる
    try {
        const urlObj = new URL(input);
        return urlObj.pathname.split('/').pop();
    } catch (e) {
        // URLではない場合、単純なパス/ファイル名として扱う
        return input.split('/').pop();
    }
}
```

## **音声の再生位置の表示**

音声の再生位置を表示し、更新する処理を作成します。

* `setAudioPosition`関数では、指定された位置を画面に表示します。
* `updateAudioPosition`関数では、1秒ごとに音声の再生位置を更新します。
* `stopUpdatingAudioPosition`関数では、音声の再生位置の更新を停止します。

```javascript
function setAudioPosition(position) {
    document.getElementById('audio_position').innerHTML = position.toFixed(2) + " sec";
}

function updateAudioPosition() {
    timer = setInterval(function() {
        setAudioPosition(audioElement.currentTime);
    }, 1000);
}

function stopUpdatingAudioPosition() {
    clearInterval(timer);
}
```

## コード全体

上記で説明したコードの全体は次のようになります。

```html
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta http-equiv="Content-Security-Policy" content="default-src * data: gap: content: https://ssl.gstatic.com; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
    <script src="components/loader.js"></script>
    <link rel="stylesheet" href="components/loader.css">
    <link rel="stylesheet" href="css/style.css">

    <script>
        // 音声ファイルとタイマーの初期化
        var audioElement;
        var srcFile = "sample.mp3";
        var timer;

        // ページ読み込み時に音声ファイルを設定し、イベントリスナーを追加する
        window.onload = function() {
            // 音声要素の初期化
            audioElement = new Audio(srcFile);

            // 音声要素に対するイベントリスナーの設定
            audioElement.addEventListener('play', updateAudioPosition, false);
            audioElement.addEventListener('pause', stopUpdatingAudioPosition, false);
            audioElement.addEventListener('ended', stopUpdatingAudioPosition, false);
        };

        // 曲を再生する関数
        function playSound() {
            const selectedSong = document.getElementById('songSelect').value;
            const selectedFilename = getFilenameFromPathOrURL(selectedSong);
            const audioFilename = getFilenameFromPathOrURL(audioElement.src);

            if (audioFilename != selectedFilename) {  
                audioElement.src = selectedSong;
            }
            audioElement.play();
        }

        // 曲を一時停止する関数
        function pauseSound() {
            audioElement.pause();
        }

        // 曲を停止（最初から再開）する関数
        function stopSound() {
            audioElement.pause();
            audioElement.currentTime = 0; // 再生位置を最初に戻す
            setAudioPosition(audioElement.currentTime);
        }

        // 音声位置を表示する関数
        function setAudioPosition(position) {
            document.getElementById('audio_position').innerHTML = position + " sec";
        }

        // 音声位置を定期的に更新する関数
        function updateAudioPosition() {
            timer = setInterval(function() {
                setAudioPosition(audioElement.currentTime);
            }, 500);
        }

        // 音声位置の更新を停止する関数
        function stopUpdatingAudioPosition() {
            clearInterval(timer);
        }

        function getFilenameFromPathOrURL(input) {
            // URLの場合として解析を試みる
            try {
                const urlObj = new URL(input);
                return urlObj.pathname.split('/').pop();
            } catch (e) {
                // URLではない場合、単純なパス/ファイル名として扱う
                return input.split('/').pop();
            }
        }
    </script>
</head>

<body style="text-align: center">
    <h1>Playing Sound</h1>
    <!-- 音声ファイルの選択 -->
    <select id="songSelect">
        <option value="song1.mp3">Song 1</option>
        <option value="https://www.learningcontainer.com/wp-content/uploads/2020/02/Kalimba.mp3">Song 2</option>
        <!-- <option value="song3.mp3">Song 3</option> -->
    </select>

    <!-- 再生、一時停止、停止ボタン -->
    <button onclick="playSound()">Play</button>
    <button onclick="pauseSound()">Pause</button>
    <button onclick="stopSound()">Stop</button><br />

    <!-- 再生位置の表示 -->
    <p id="audio_position"></p>
</body>
</body>

</html>

```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ja.docs.monaca.io/sampleapp/tips/media.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
