Search code examples
vb.netaudiotimerirrklang

Update text of textblock in every sec in VB Net


I have a Sub, which handled when I create my new window. It loads and plays an mp3 file using Irrklang library. But how to update the playposition. I heard that i can use timer, but how to use it inside a sub?

Private Sub  MainWindow_Loaded(sender As Object, e As RoutedEventArgs)

    Dim Music = MyiSoundengine.Play2D("Music/001.mp3")

    I Want to update this in every sec!
    Dim Music_Playposition = Music.Playpostion

    End Sub

Solution

  • You cannot use a timer inside of a method/sub. The only way that a timer works is by periodically raising events; in the case of a timer, it's called the "Tick" event, raised each time that the timer "ticks".

    You probably already know what events are—your MainWindow_Loaded method is handling one, the Loaded event of the MainWindow class.

    So what you need to do is add a timer to your application, handle its Tick event, and inside that event handler update your textbox with the current position.

    For example:

    Public Class MainWindow
    
        Private WithEvents timer As New System.Windows.Threading.DispatcherTimer()
    
        Public Sub New()
            ' Initialize the timer.
            timer.Interval = new TimeSpan(0, 0, 1);  ' "tick" every 1 second
    
            ' other code that goes in the constructor
            ' ...
        End Sub
    
        Private Sub timer_Tick(sender As Object, e As EventArgs) Handles timer.Tick
            ' TODO: Add code to update textbox with current position
        End Sub
    
        Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs)
            ' Start the timer first.
            timer.Start()
    
            ' Then start playing your music.
            MyiSoundengine.Play2D("Music/001.mp3")
        End Sub
    
        ' any other code that you need inside of your MainWindow class
        ' ...
    
    End Class
    

    Note the use of the WithEvents keyword in the class-level declaration of the timer object. That makes it easy to handle its events using only Handles statements on the event handler. Otherwise, you have to use AddHandler inside of the constructor to wire up the event handler methods to the desired events.