0
0

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 1 year has passed since last update.

Javascriptによる自動作曲

Posted at

簡単な自動作曲アプリケーションです。再生ボタンの回数でレイヤー再生が可能です。

自動作曲アプリケーション

自動作曲アプリケーション

音楽を生成 再生
<script>
    // 音符の定義
    const notes = ["C4", "D4", "E4", "F4", "G4", "A4", "B4"];

    // 生成された音楽の格納用
    let generatedMusic = [];

    // 音楽を生成する関数
    function generateMusic() {
        generatedMusic = [];
        for (let i = 0; i < 16; i++) { // 16拍分の音楽を生成
            const randomNote = notes[Math.floor(Math.random() * notes.length)];
            generatedMusic.push(randomNote);
        }
    }

    // 音楽を再生する関数
    function playMusic() {
        if (generatedMusic.length === 0) {
            alert("音楽を先に生成してください。");
            return;
        }

        let index = 0;
        const audioContext = new AudioContext();

        function playNextNote() {
            if (index < generatedMusic.length) {
                const note = generatedMusic[index];
                const oscillator = audioContext.createOscillator();
                oscillator.type = "sine";
                oscillator.frequency.setValueAtTime(noteToFrequency(note), audioContext.currentTime);
                oscillator.connect(audioContext.destination);
                oscillator.start();
                oscillator.stop(audioContext.currentTime + 0.5); // 0.5秒間音を鳴らす
                index++;
                setTimeout(playNextNote, 500); // 0.5秒後に次の音符を再生
            }
        }

        playNextNote();
    }

    // 音符を周波数に変換する関数
    function noteToFrequency(note) {
        const noteToIndex = {
            "C4": 261.63,
            "D4": 293.66,
            "E4": 329.63,
            "F4": 349.23,
            "G4": 392.00,
            "A4": 440.00,
            "B4": 493.88
        };
        return noteToIndex[note];
    }

    // ボタンクリック時のイベントリスナー
    document.getElementById("generateButton").addEventListener("click", generateMusic);
    document.getElementById("playButton").addEventListener("click", playMusic);
</script>
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?