Strange problem with storing javascript buffer pointers in a list

Just starting out? Need help? Post your questions and find answers here.
Andy
Posts: 38
Joined: Sat Feb 15, 2020 5:19 pm
Location: Larnaca, Cyprus
Contact:

Strange problem with storing javascript buffer pointers in a list

Post by Andy »

see code comments for details

Code: Select all

Structure samples
  buffer.l  
EndStructure

Global NewList sample.samples(), audioctx

Procedure ButtonHandler()
  Static audioinit
  
  If audioinit = 0
    audioinit = 1
    ! const AudioContext = window.AudioContext || window.webkitAudioContext
    ! v_audioctx = new AudioContext({latencyHint: 0})
    ! console.log(v_audioctx)
    
    samplelength = 10000
    
    *samplebuffer = AllocateMemory(44 + samplelength)
    PokeS(*samplebuffer, 0, "RIFF", -1, #PB_Ascii|#PB_String_NoZero)
    PokeL(*samplebuffer, 4, 36 + samplelength)
    PokeS(*samplebuffer, 8, "WAVE", -1, #PB_Ascii|#PB_String_NoZero)
    PokeS(*samplebuffer, 12, "fmt ", -1, #PB_Ascii|#PB_String_NoZero)
    PokeL(*samplebuffer, 16, 16)
    PokeW(*samplebuffer, 20, 1)
    PokeW(*samplebuffer, 22, 1)
    PokeL(*samplebuffer, 24, 16726.84)
    PokeL(*samplebuffer, 28, 16726.84)
    PokeW(*samplebuffer, 32, 1)
    PokeW(*samplebuffer, 34, 8)
    PokeS(*samplebuffer, 36, "data", -1, #PB_Ascii|#PB_String_NoZero)
    PokeL(*samplebuffer, 40, samplelength)
    
    For samplebuffer = 0 To samplelength
      PokeA(*samplebuffer, samplecount + 44, Random(255, 0))
      samplecount + 1
    Next
    
    AddElement(sample())
    
    ! v_audioctx.decodeAudioData(p_samplebuffer, function(v_buffer) {
    sample()\buffer = buffer
    Debug sample()\buffer ;<--- buffer pointer is printed
    ! })
    
    Debug sample()\buffer ;<--- this prints 0
    
    FreeMemory(*samplebuffer)
    DisableGadget(0, 1)
  EndIf
    
EndProcedure

Procedure ButtonHandler1()
  
  FirstElement(sample())
  mybuffer = sample()\buffer
  
  ! v_source = v_audioctx.createBufferSource()
  ! v_source.buffer = v_mybuffer
  ! v_source.connect(v_audioctx.destination)
  ! v_source.start()
      
EndProcedure

If OpenWindow(0, 0, 0, 300, 100, "Audio Buffer Test", #PB_Window_ScreenCentered)
  ButtonGadget(0, 10, 10, 280, 30, "Generate Buffer")
  ButtonGadget(1, 10, 60, 280, 30, "Play Stored Buffer")
EndIf

BindGadgetEvent(0, @ButtonHandler())
BindGadgetEvent(1, @ButtonHandler1())