VisualHMI 音频播放:play_sound 系列与 MP3 自动连播

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

音频播放 API:播放 SD/U 盘里的音乐文件,配合播放器控件做完全的音乐播放器(播放/暂停/上下首/progress bar/音量)。

1. API 总表

函数説明
play_sound(filename)播放音频,绝对路径(如 "1:/music/xx.mp3")
stop_sound()停止播放
pause_sound()暂停
resume_sound()继续播放

2. 播放器控件アドレス表

Address用途
LW1000左右翻页
LW1001上一首/下一首
LW1002播放/暂停(位ステータス指示灯:0-暂停/1-继续)
LW1003当前页
LW1004总页数
LW1005SD 根目录ありますか?歌(位ステータス)
LW1100~1200歌名文本リスト
LW1240播放当前时间
LW1250总时间
LW1006播放プログレスバー
LW0140音量

3. 遍历 SD 卡歌曲

musicNameListTb = {}      -- 歌名リスト缓存
curPlayIndex = 1

function on_sd_inserted(dir)
  list_dir(dir)           -- 列 SD 卡根目录
end

function on_list_dir(path, filename, type, fsize)
  if type == 1 then
    local ext = string.sub(filename, -4)
    if ext == ".mp3" or ext == ".wav" then
      table.insert(musicNameListTb, filename)
      set_uint16(VT_LW, 0x1005, 1)   -- 有歌标志
    end
  end
end

4. 播放控制逻辑

function on_update(slave, vtype, addr)
  if vtype == VT_LW then
    if addr == 0x1002 then
      local v = get_uint16(VT_LW, 0x1002)
      if v == 1 then
        play_sound("1:/music/"..musicNameListTb[curPlayIndex])
      else
        pause_sound()
      end
    elseif addr == 0x1001 then
      -- 上一首/下一首:Switch curPlayIndex 后重新播放
      local v = get_uint16(VT_LW, 0x1001)
      if v == 1 and curPlayIndex > 1 then
        curPlayIndex = curPlayIndex - 1
      elseif v == 2 and curPlayIndex < #musicNameListTb then
        curPlayIndex = curPlayIndex + 1
      end
      play_sound("1:/music/"..musicNameListTb[curPlayIndex])
    end
  end
end

function on_run(screen)
  updatMisPlayState()     -- 检测播放ステータス,播完自动下一首
end
三个坑:①路径必须带デバイス前缀(M 系列 1:=SD/2:=U盘/3:=内部Flash),「1:/music/a.mp3」对、「1:music/a.mp3」错;②播放完不会自动切下一首,要自己在 on_run 里ポーリング播放ステータス(on_video_notify 类似机制);③音频格式按固件サポートリスト来,サポートなし。的格式会静默失敗——先拿一个已知能播的文件试。

整理自 广州大彩科技 VisualHMI 开发ドキュメント(hmi-doc.gz-dc.com)LUA Tutorial「音频播放」,著作権は大彩科技すべての。

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.