Advertisement
colhaydutu

Untitled

Jan 27th, 2024 (edited)
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. local peripheral = peripheral
  2. local dfpwm = require("cc.audio.dfpwm")
  3. local modem = peripheral.wrap("back")
  4.  
  5. modem.open(11)
  6.  
  7. -- Function to find connected speakers
  8. local function findConnectedSpeakers()
  9. local speakers = {}
  10. local allPeripherals = peripheral.getNames()
  11.  
  12. for _, pName in ipairs(allPeripherals) do
  13. local pType = peripheral.getType(pName)
  14. if pType == "speaker" then
  15. table.insert(speakers, peripheral.wrap(pName))
  16. end
  17. end
  18.  
  19. return speakers
  20. end
  21.  
  22. -- Function to read chunks from a string
  23. local function stringChunks(str, chunkSize)
  24. local start = 1
  25. return function()
  26. if start > #str then
  27. return nil
  28. else
  29. local chunk = str:sub(start, start + chunkSize - 1)
  30. start = start + chunkSize
  31. return chunk
  32. end
  33. end
  34. end
  35.  
  36. -- Main function to play music on connected speakers
  37. local function playMusicOnSpeakers()
  38. local connectedSpeakers = findConnectedSpeakers()
  39.  
  40. if #connectedSpeakers == 0 then
  41. print("No speakers found. Please make sure speakers are connected.")
  42. return
  43. end
  44.  
  45. print("Please enter the URL of the music file you want to play:")
  46. local url = read()
  47.  
  48. local response = http.get(url, nil, true)
  49.  
  50. if not response then
  51. print("Request failed. HTTP Error: " .. (response and response.getResponseCode() or "Unknown"))
  52. return
  53. end
  54.  
  55. local responseData = response.readAll()
  56. response.close()
  57.  
  58. local decoder = dfpwm.make_decoder()
  59. local chunkSize = 16 * 1024
  60. local chunkGenerator = stringChunks(responseData, chunkSize)
  61. local chunk = chunkGenerator()
  62.  
  63. while chunk do
  64. local buffer = decoder(chunk)
  65.  
  66. for _, speaker in ipairs(connectedSpeakers) do
  67. while not speaker.playAudio(buffer) do
  68. os.pullEvent("speaker_audio_empty")
  69. end
  70. end
  71.  
  72. chunk = chunkGenerator()
  73. end
  74.  
  75. print("Music successfully played on all speakers.")
  76. end
  77.  
  78. -- Call the main function to play music
  79. playMusicOnSpeakers()
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement