nodeMCU播放音乐《两只老虎》

-- 喇叭接到D1和GND端即可

-- 播放音乐
function playMusic(pin, score)
    print("Play music", #score)
    local duration = 100 -- 播放时长
    -- 遍历所有音符
    for _,note in pairs(score) do
        if(note < 0) then
            duration = math.abs(note)
        else
            if(note > 0) then -- 大于0才播放                   
                pwm.setup(pin, note, 1023)
                pwm.setduty(pin, 1000)
            end
            tmr.delay(duration * 1000)
            pwm.stop(pin)
        end
    end
    pwm.close(pin)
    print("Play finished.")
end

-- 初始化音符变量
-- 如C3,F4(中央C为C4,可简写为C)
function initNotes()
    local RATES = {
        131,147,165,175,196,220,247, -- 低音频率
        262,294,330,349,392,440,493, -- 中音频率
        523,587,659,698,784,880,988, -- 高音频率
    }
    local NOTES = {'C', 'D', 'E', 'F', 'G', 'A', 'B'}
    for i=0,2 do
        for j,note in pairs(NOTES) do
            local name = note .. (i + 3)
            _G[name] = RATES[i * 7 + j]
            if(i == 1) then
                _G[note] = _G[name]
            end
        end
    end
end

initNotes()
-- 《两只老虎》乐谱
-- 0为休止符,负值为播放时长(的相反数)
local score = {
    -400,C,D,E,C,C,D,E,C,
    -400,E,F,G,0,E,F,G,0,
    -200,G,A,G,F,-400,E,C,
    -200,G,A,G,F,-400,E,C,
    -400,D,G3,C,0,D,G3,C,0,
}

local PIN = 1 -- 管脚 D1
playMusic(PIN, score)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容