Playsound in Thread Advice

Just starting out? Need help? Post your questions and find answers here.
collectordave
Addict
Addict
Posts: 1309
Joined: Fri Aug 28, 2015 6:10 pm
Location: Portugal

Playsound in Thread Advice

Post by collectordave »

Just looking at my media player and thought if i could play the sound in a thread my application could get on with other things so just trying it out.

Trying the following code can someone just check to see if I am missing anything as I am not used to threads. Seems to work ok.

Code: Select all

InitSound()
UseOGGSoundDecoder()

Global FileName.s
Global CurrentSound.i,CurrentLength.i

Global Thread.i,SongCommand.i,SongStatus.i

Enumeration 100
  #Pause
  #Resume
  #Stop
EndEnumeration



Procedure PlaySong(*Sound)
  
  Debug *Sound
  
  PlaySound(*Sound)

  While SoundStatus(CurrentSound) <> #PB_Sound_Stopped
    
  If SongCommand = #Pause
    PauseSound(*Sound)
  EndIf    
  If SongCommand = #Resume
    ResumeSound(*Sound)
  EndIf
  If SongCommand = #Stop
   StopSound(*Sound)
  EndIf  
  SongStatus = SoundStatus(*Sound)
  
  Wend
  
  If IsSound(*Sound)
    FreeSound(*Sound)
  EndIf
  SongStatus = -1
  
EndProcedure



FileName = "10cc - Art For Art's Sake.ogg"

CurrentSound = LoadSound(#PB_Any, FileName)
CurrentLength = SoundLength(CurrentSound, #PB_Sound_Millisecond) 

Thread = CreateThread(@PlaySong(), CurrentSound)

OpenWindow(0,10,10,100,100,"Play")
ButtonGadget(1,5,5,60,25,"Pause")
ButtonGadget(2,5,35,60,25,"Resume")
ButtonGadget(3,5,65,60,25,"Stop")

Repeat
    Event = WaitWindowEvent()
    
    Select Songstatus
        
      Case -1
        
        Debug "No Sound"
        
      Case 0
        
        Debug "Stopped"
        
      Case  1
        
        Debug "Playing"
        
      Case 2
        
        Debug "Paused"

        
    EndSelect
    

    
    If EventGadget() = 1
      
      SongCommand = #Pause

    EndIf
    
      If EventGadget() = 2
      
      SongCommand = #Resume

    EndIf 
    
    If EventGadget() = 3
      
      SongCommand = #Stop  

    EndIf    
    
    
  Until Event = #PB_Event_CloseWindow
  
  If IsThread(Thread)
    SongCommand = #Stop
    Debug "Thread Still Active!"
  EndIf
Any intelligent fool can make things bigger and more complex. It takes a touch of genius — and a lot of courage to move in the opposite direction.
infratec
Always Here
Always Here
Posts: 6873
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Playsound in Thread Advice

Post by infratec »

In general it's ok.

I prefer to use a structure as parameter, then you don't need a global variable for stopping the thread,
An I also store the thread itself in the structure like:

Code: Select all

Structure ThreadParameterStructure
  Thread.i
  Sound.i
  Exit.i
EndStructure

Procedure SoundThread(*Parameter.ThreadParameterStructure)
Post Reply