アットウィキロゴ

サウンドを再生する方法

ここでは、Playdateでサウンドを再生する基本的な方法についてまとめます。


BGM (MP3) 再生の基本

BGM (MP3) を再生する方法について説明します。
BGMは基本的に長めの音声ファイルでメモリ上にすべて読み込むのはメモリを圧迫する可能性があります。そこで、playdate.sound.fileplayerを使用してストリーム再生します。
サウンドの配置
今回使用するサウンドファイルです。
bgm.mp3
これを "source/sounds" に配置します。
BGM再生 (ストリーム) の基本コード
BGM (長めの音声) を (ストリーム) 再生する基本的なコードは以下のとおりです。
playdate.sound.fileplayerを生成し、play()関数を呼び出します。
new() にファイルパスを指定すると、自動で読み込んでくれます。このとき拡張子はあってもなくても問題ないようです。
import "CoreLibs/graphics"
 
local pd <const> = playdate
-- オーディオファイルの読み込み.
local musicPlayer = pd.sound.fileplayer.new("sounds/bgm")
 
function pd.update()
    if pd.buttonJustPressed(pd.kButtonA) then
        -- サウンドの再生
        musicPlayer.play()
    end
end
 
ループ再生する
ただこのままだと1回しか再生してくれません。BGMで繰り返し再生したい場合は play() の引数に「0」を指定します。
play()の引数は「繰り返し回数」で、0を指定すると無限に繰り返すためループ再生となります。
import "CoreLibs/graphics"
 
local pd <const> = playdate
-- オーディオファイルの読み込み.
local musicPlayer = pd.sound.fileplayer.new("sounds/bgm")
 
function pd.update()
    if pd.buttonJustPressed(pd.kButtonA) then
        -- サウンドの再生
        musicPlayer.play(0) -- "0" は繰り返し回数を無限
    end
end
 

Tips

BGMを再生しているかどうか・再生位置の計算
isPlaying() でBGMを再生中かどうかを判定でき、getOffset()で再生位置、getLength()で全体の長さを取得できます。
import "CoreLibs/graphics"
 
local pd <const> = playdate
local gfx <const> = pd.graphics
-- オーディオファイルの読み込み.
local musicPlayer = pd.sound.fileplayer.new("sounds/bgm")
 
function pd.update()
    if pd.buttonJustPressed(pd.kButtonA) then
        if musicPlayer:isPlaying() then
            musicPlayer:stop() -- 再生していたら停止.
        else
            musicPlayer:play(0) -- 再生していなければ先頭から再生.
        end
    end
 
    gfx.clear()
    if musicPlayer:isPlaying() then
        -- 再生位置の描画.
        -- 現在の位置.
        local now = musicPlayer:getOffset()
        -- 全体の長さ.
        local total = musicPlayer:getLength()
        -- 進捗バーの描画.
        local w = now / total * 400
        gfx.fillRect(0, 10, w, 16)
        -- テキストの描画.
        gfx.drawText("Playing: " .. math.floor(now) .. " / " .. math.floor(total), 10, 40)
    end
end
 

参考

関連ページ

最終更新:2026年04月25日 11:46
添付ファイル