Advertisement
colhaydutu

new speaker

Jan 16th, 2024 (edited)
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. local peripheral = peripheral or require("peripheral")
  2.  
  3. local http = http or require("http")
  4.  
  5. local dfpwm = require("cc.audio.dfpwm")
  6.  
  7.  
  8.  
  9. local speaker = peripheral.find("speaker")
  10.  
  11.  
  12.  
  13. if not speaker then
  14.  
  15. print("Speaker not found. Please make sure a speaker is connected.")
  16.  
  17. return
  18.  
  19. end
  20.  
  21.  
  22.  
  23. local function stringChunks(str)
  24.  
  25. local chunkSize = 16 * 1024
  26.  
  27. local start = 1
  28.  
  29. return function()
  30.  
  31. if start > #str then
  32.  
  33. return nil
  34.  
  35. else
  36.  
  37. local chunk = str:sub(start, start + chunkSize - 1)
  38.  
  39. start = start + chunkSize
  40.  
  41. return chunk
  42.  
  43. end
  44.  
  45. end
  46.  
  47. end
  48.  
  49.  
  50.  
  51. local function saveToFile(filename, data)
  52.  
  53. local file = fs.open(filename, "w")
  54.  
  55. file.write(data)
  56.  
  57. file.close()
  58.  
  59. end
  60.  
  61.  
  62.  
  63. print("Please enter the URL of the music file you want to play:")
  64.  
  65. local url = read()
  66.  
  67.  
  68.  
  69. local response = http.get(url, nil, true)
  70.  
  71.  
  72.  
  73. if response then
  74.  
  75. local responseData = response.readAll()
  76.  
  77. response.close()
  78.  
  79.  
  80.  
  81. local decoder = dfpwm.make_decoder()
  82.  
  83.  
  84.  
  85. print("Press Enter to start playing the music.")
  86.  
  87. read()
  88.  
  89.  
  90.  
  91. for chunk in stringChunks(responseData) do
  92.  
  93. local buffer = decoder(chunk)
  94.  
  95.  
  96.  
  97. while not speaker.playAudio(buffer, 1) do
  98.  
  99. os.pullEvent("speaker_audio_empty")
  100.  
  101. end
  102.  
  103.  
  104.  
  105. saveToFile("output_audio.dfpwm", chunk)
  106.  
  107. end
  108.  
  109.  
  110.  
  111. print("Music finished playing.")
  112.  
  113. else
  114.  
  115. print("Request failed. HTTP Error: " .. (response and response.getResponseCode() or "Unknown"))
  116.  
  117. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement