LoginSignup
1
0

More than 1 year has passed since last update.

【Playdate】マイク録音して再生するシンプルサンプラーを作る

Posted at

Playdateにはマイク入力があり録音関連のAPIもあります。
今回は3秒間の短いサンプリングをするサンプルを作ってみます。

main.lua
import "CoreLibs/object"
import "CoreLibs/graphics"
import "CoreLibs/sprites"
import "CoreLibs/timer"

local gfx <const> = playdate.graphics

local secondsToRecord <const> = 3

local buffer = nil
local sound = nil
local status = nil
local isRec = false

-- 録音完了後処理
local completionCallback = function()
	isRec = false
	status = "REC END"
	
	playdate.sound.micinput.stopListening()
	sound = playdate.sound.sampleplayer.new(buffer)
	sound:setFinishCallback(function()
		status = "STOP"
		gfx.sprite.redrawBackground()
	end)
	
	gfx.sprite.redrawBackground()
end

-- 録音開始処理
function startRec()
	isRec = true
	status = "REC"
	
	playdate.sound.micinput.startListening() -- マイク入力開始
	buffer = playdate.sound.sample.new(secondsToRecord, playdate.sound.kFormat16bitMono) -- バッファ
	playdate.sound.micinput.recordToSample(buffer,completionCallback) -- 録音
	
	gfx.sprite.redrawBackground()
end

function myGameSetUp()
	gfx.sprite.setBackgroundDrawingCallback(
		function( x, y, width, height )
			gfx.drawText(status, 20, 20)
		end
	)
	
	startRec()
end

myGameSetUp()

function playdate.update()
	-- Aボタン: 録音再生
	if playdate.buttonIsPressed(playdate.kButtonA) then
		if sound ~= nil then
			if sound:isPlaying() ~= true then
				status = "PLAY!"
				sound:play(1)
				gfx.sprite.redrawBackground()
			end
		end
	end
	
	-- Bボタン: 録音
	if playdate.buttonIsPressed(playdate.kButtonB) then
		if isRec ~= true then
			startRec()
		end
	end

	gfx.sprite.update()
	playdate.timer.updateTimers()

end

startRec関数内で実行している主な処理内容を見ていきます。
playdate.sound.micinput.startListening():マイク入力レベルの監視開始
playdate.sound.sample.new(secondsToRecord, playdate.sound.kFormat16bitMono):バッファオブジェクト生成
playdate.sound.micinput.recordToSample(buffer,completionCallback):録音開始。第一引数にバッファオブジェクト、第二引数に録音終了後のコールバック関数。

前述のコールバック関数completionCallbackでの主な処理内容は以下のとおりです。
playdate.sound.micinput.stopListening():マイク入力レベルの監視終了
playdate.sound.sampleplayer.new(buffer):録音したバッファオブジェクトからsamplePlayerオブジェクトを生成
sound:setFinishCallback(callbackFunction):samplePlayerオブジェクトの再生終了後のコールバック関数のセット

録音したsamplePlayerオブジェクトの再生と再録音処理はplaydate.update()にて実行しています。

1
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
1
0