Advertisement
GroupXyz

Audioplayer (2.0) for Computercraft

Feb 4th, 2024
2,108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. -- Audioplayer script by GroupXyz
  2.  
  3. -- Version: 2.0
  4. -- Play audio files!
  5.  
  6. function loadFileList(interface)
  7. local fileList = {}
  8. for _, file in ipairs(fs.list(interface)) do
  9. if not fs.isDir(interface.."/"..file) then
  10. table.insert(fileList, file)
  11. end
  12. end
  13. return fileList
  14. end
  15.  
  16. function displayFileList(fileList)
  17. term.clear()
  18. term.setCursorPos(1, 1)
  19. print("----------Audioplayer by GroupXyz----------")
  20. print("Please place your audio files in the folder 'sounds/'")
  21. print("Files:")
  22. for i, file in ipairs(fileList) do
  23. print(i..". "..file)
  24. end
  25. end
  26.  
  27. function playFile(interface, selectedFile, loop)
  28. local filePath = interface.."/"..selectedFile
  29. if fs.exists(filePath) and not fs.isDir(filePath) then
  30. local speaker = peripheral.find("speaker")
  31. if speaker then
  32. local dfpwm = require("cc.audio.dfpwm")
  33. local decoder = dfpwm.make_decoder()
  34.  
  35. local function playBuffer(buffer)
  36. while not speaker.playAudio(buffer) do
  37. os.pullEvent("speaker_audio_empty")
  38. end
  39. end
  40.  
  41. if loop then
  42. while true do
  43. for chunk in io.lines(filePath, 16 * 1024) do
  44. local buffer = decoder(chunk)
  45. playBuffer(buffer)
  46. sleep(0.05)
  47. end
  48. end
  49. else
  50. for chunk in io.lines(filePath, 16 * 1024) do
  51. local buffer = decoder(chunk)
  52. playBuffer(buffer)
  53. sleep(0.05)
  54. end
  55. end
  56.  
  57. print("File played successfully.")
  58. else
  59. print("Speaker not found.")
  60. end
  61. else
  62. print("File not found.")
  63. end
  64. end
  65.  
  66. function createInterface(interface)
  67. if not fs.exists(interface) then
  68. fs.makeDir(interface)
  69. end
  70. end
  71.  
  72. -- Main program
  73. local interface = "sounds/"
  74. createInterface(interface)
  75. local fileList = loadFileList(interface)
  76.  
  77. while true do
  78. displayFileList(fileList)
  79. print("Which file do you want to play? (Type 'repeat' to loop, 0 to exit)")
  80. local choice = read()
  81.  
  82. if choice == "0" then
  83. break
  84. elseif choice == "repeat" then
  85. print("Enter the file number to repeat:")
  86. local repeatChoice = tonumber(read())
  87. if fileList[repeatChoice] then
  88. playFile(interface, fileList[repeatChoice], true)
  89. else
  90. print("Invalid selection.")
  91. end
  92. elseif tonumber(choice) and fileList[tonumber(choice)] then
  93. playFile(interface, fileList[tonumber(choice)], false)
  94. else
  95. print("Invalid selection.")
  96. end
  97. end
  98.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement