AudioUtils.lua 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. --Audio Utilities
  2. --Localized Lua Library
  3. local floor = math.floor
  4. --The API
  5. local AudioUtils = {}
  6. -- C# D# F# G# A#
  7. --C D E F G A B
  8. --Convert from waveform id to waveform name, and vice versa.
  9. AudioUtils.Waves = {
  10. "Square", "Pulse", "Sawtooth", "Triangle", "Noise";
  11. [-1] = "Silent", [0] = "Sine"
  12. }
  13. for i=-1,5 do
  14. AudioUtils.Waves[AudioUtils.Waves[i]] = i
  15. end
  16. --Convert from note letter to note number and vice versa.
  17. AudioUtils.Notes = {
  18. "C","C#","D","D#","E","F","F#","G","G#","A","A#","B"
  19. }
  20. for i=1,12 do
  21. AudioUtils.Notes[AudioUtils.Notes[i]] = i
  22. end
  23. --Convert from note+oct to frequency.
  24. --note can be the note name or note number (1,12), oct can be from 0 to 7.
  25. local noteFreqConst, noteFreqCache = 2^(1/12), {}
  26. function AudioUtils.noteFrequency(note,oct)
  27. if type(note) == "string" then
  28. note = AudioUtils.Notes[note]
  29. end
  30. note,oct = floor(note), floor(oct)
  31. if noteFreqCache[note.."x"..oct] then return noteFreqCache[note.."x"..oct] end
  32. local notepos = (oct)*12+note
  33. local notedist = notepos - 58
  34. local notehz = 440 --A4
  35. if notedist < 0 then
  36. for i=1,-notedist do
  37. notehz = notehz/noteFreqConst
  38. end
  39. elseif notedist > 0 then
  40. for i=1,notedist do
  41. notehz = notehz*noteFreqConst
  42. end
  43. end
  44. noteFreqCache[note.."x"..oct] = notehz
  45. return notehz
  46. end
  47. function AudioUtils.frequencyNote(freq)
  48. for oct=0,7 do
  49. for note=1,12 do
  50. local nfreq = AudioUtils.noteFrequency(note,oct)
  51. if nfreq >= freq then
  52. return note, oct
  53. end
  54. end
  55. end
  56. return 12, 7
  57. end
  58. --Make the AudioUtils a global
  59. _G["AudioUtils"] = AudioUtils