locked
Onended Event in <Audio> control RRS feed

  • Question

  • User-1653812950 posted

    The following code loads songs from a "Song" folder into a Listbox. I can click on one of the songs, and it will play using the <Audio> control. However, the onended Event calls for a JavaScript function, but all of my code is in VBScript. Is there a way to call a VBScript sub-rountine from withing this onended event?

    Here's the code:

    <script language="vbscript" runat="server">
    
        Public SongToPlay As String
        
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            If Not IsPostBack Then ' First time ASPX page is loaded.
                
                SongToPlay = "Songs/Song1.mp3"
                
                Dim pathLocal As String
                Dim pathSongs As String
                
                ' Get current path
                pathLocal = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ServerVariables("PATH"))
                pathSongs = pathLocal & "\Songs"
                
                Dim MyFile, MyPath As String
                MyPath = pathSongs   ' Set Folder location for songs
                MyFile = Dir(pathSongs & "\*.mp3")
                
                Do While MyFile <> ""   ' Start the loop.
                    ' Use bitwise comparison to make sure MyName is a directory.
                    lbAllSongs.Items.Add(MyFile)
                    MyFile = Dir()   ' Get next entry.
                Loop
    
                lbAllSongs.SelectedIndex = 0 ' Sets first song as default 
                
            Else
                
                lblSelectedSong.Text = lbAllSongs.SelectedItem.Text
                SongToPlay = "Songs/" & lbAllSongs.SelectedItem.Text
            
            End If '  If Not IsPostBack
            
        End Sub ' Page_Load
        
        Protected Sub btnSelectSong_Click(ByVal Source As Object, ByVal E As EventArgs)
    
            ' TEXT SHOWS IN POSTBACK
    
        End Sub
        
        Protected Sub audioPlayerOnEnded()
            
            lblSelectedSong.Text = "song is done."
            
        End Sub
    
    </script>

    Here is the HTML Code:

    <audio id="audioPlayer" src="<%=SongToPlay %>" controls="true" onended="audioPlayerOnEnded()"></audio>

    When I try using this code, it will not activate the audioPlayerOnEnded sub-routine. Suggestions?

    My goal is to play all the songs in the list automatically as soon as one song is finished.

    Thanks in advance for any useful tips.

    Tuesday, February 25, 2020 10:12 PM

Answers

  • User-1330468790 posted

    Hi, qwsoftdraw,

    Generally speaking, you can not directly call a non-static method of code behind file from the client-side.

    However, I could provide you with a workaround that you can use "_doPostBack" and add parameters for the Javascript function. Then it will trigger a postback and pass the parameters back to the server side so that you can check them in Page_Load event and call functions from server side.

    Besides, I add an attribute "autoplay" to <audio> so that it will automatically play mp3. If you don't need that, just remove it.

    More details, you could find in below code.

    Details about _doPostBack: (which will be rendered in page by .NET Framework)

    <script type="text/javascript">
    
    //<![CDATA[
    
    var theForm = document.forms['form1'];
    
    if (!theForm) {
    
        theForm = document.form1;
    
    }
    
    function __doPostBack(eventTarget, eventArgument) {
    
        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
    
            theForm.__EVENTTARGET.value = eventTarget;
    
            theForm.__EVENTARGUMENT.value = eventArgument;
    
            theForm.submit();
    
        }
    
    }
    
    //]]>
    
    </script>

    AudioAutoPlayDemo:

    .aspx Page:

    <head runat="server">
    
        <title></title>
    
        <script type="text/javascript">
    
            //This function name is the same as that in server side but only works in client-side
    
            function audioPlayerOnEnded() {
    
                javascript: __doPostBack('audioPlayer', '');
    
            }
    
        </script>
    
    </head>
    
    <body>
    
        <form id="form1" runat="server">
    
            <div>
    
                <asp:DropDownList ID="lbAllSongs" runat="server" AutoPostBack="true"></asp:DropDownList> <asp:Label ID="lblSelectedSong" runat="server"></asp:Label>
    
     
    
                <br />
    
                <audio id="audioPlayer" autoplay src="<%=SongToPlay %>" controls="true" onended="audioPlayerOnEnded()">Your browser does not support the
    
                <code>audio</code> element.</audio>
    
            </div>
    
        </form>
    
    </body>

    Code Behind:

    Public SongToPlay As String
    
     
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            If Not IsPostBack Then
    
                Dim pathLocal As String
    
                Dim pathSongs As String
    
                pathLocal = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ServerVariables("PATH"))
    
                pathSongs = pathLocal & "\Songs"
    
                Dim MyFile, MyPath As String
    
                MyPath = pathSongs
    
                MyFile = FileSystem.Dir(pathSongs & "\*.mp3")
    
     
    
                While MyFile <> ""
    
                    lbAllSongs.Items.Add(MyFile)
    
                    MyFile = FileSystem.Dir()
    
                End While
    
     
    
                lbAllSongs.SelectedIndex = 0
    
                SongToPlay = "Songs/" & lbAllSongs.SelectedItem.Text
    
            Else
    
     
    
                If Request.Form("__EVENTTARGET") = "audioPlayer" Then
    
                    audioPlayerOnEnded()
    
                Else
    
                    lblSelectedSong.Text = lbAllSongs.SelectedItem.Text
    
                    SongToPlay = "Songs/" & lbAllSongs.SelectedItem.Text
    
                End If
    
            End If
    
     
    
        End Sub
    
     
    
        Protected Sub btnSelectSong_Click(ByVal Source As Object, ByVal E As EventArgs)
    
        End Sub
    
     
    
        //This name is the same as the one in page but is works only in server side.
    
        Protected Sub audioPlayerOnEnded()
    
            Dim nextIndex As Integer = findNextIndex()
    
            lbAllSongs.SelectedIndex = nextIndex
    
            lblSelectedSong.Text = lbAllSongs.SelectedItem.Text
    
            SongToPlay = "Songs/" & lbAllSongs.SelectedItem.Text
    
        End Sub
    
     
    
        Private Function findNextIndex() As Integer
    
            Dim current As Integer = lbAllSongs.SelectedIndex
    
            Dim nextIndex As Integer
    
     
    
            If current + 1 > lbAllSongs.Items.Count - 1 Then
    
                nextIndex = 0
    
            Else
    
                nextIndex = current + 1
    
            End If
    
     
    
            Return nextIndex
    
        End Function

    Demo:

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 26, 2020 6:39 AM
  • User-1330468790 posted

    Hi, qwsoftdraw,

     

    I tried the code on the firefox browser 72.0.1 and reproduced the problem. 

    After checking the settings of the firefoxI found that the reason why 'autoplay' is not working in your side is that the firefox browser blocks the autoplay by default.

     

    If you want to change this setting, you could follow the steps as below:

    1.Click the open menu on the top right corner of the browser and Choose 'Privacy Protection';

    2. Click into 'Manage Settings';

    3. Scroll down to 'Permissions' Section and choose the settings of 'AutoPlay;

    4. Set Default for all websites: 'Allow Audio and Video'; Or you can set for special websites.

    I checked for the previous code again and the problem has gone.

     

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 28, 2020 9:41 AM

All replies

  • User-1330468790 posted

    Hi, qwsoftdraw,

    Generally speaking, you can not directly call a non-static method of code behind file from the client-side.

    However, I could provide you with a workaround that you can use "_doPostBack" and add parameters for the Javascript function. Then it will trigger a postback and pass the parameters back to the server side so that you can check them in Page_Load event and call functions from server side.

    Besides, I add an attribute "autoplay" to <audio> so that it will automatically play mp3. If you don't need that, just remove it.

    More details, you could find in below code.

    Details about _doPostBack: (which will be rendered in page by .NET Framework)

    <script type="text/javascript">
    
    //<![CDATA[
    
    var theForm = document.forms['form1'];
    
    if (!theForm) {
    
        theForm = document.form1;
    
    }
    
    function __doPostBack(eventTarget, eventArgument) {
    
        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
    
            theForm.__EVENTTARGET.value = eventTarget;
    
            theForm.__EVENTARGUMENT.value = eventArgument;
    
            theForm.submit();
    
        }
    
    }
    
    //]]>
    
    </script>

    AudioAutoPlayDemo:

    .aspx Page:

    <head runat="server">
    
        <title></title>
    
        <script type="text/javascript">
    
            //This function name is the same as that in server side but only works in client-side
    
            function audioPlayerOnEnded() {
    
                javascript: __doPostBack('audioPlayer', '');
    
            }
    
        </script>
    
    </head>
    
    <body>
    
        <form id="form1" runat="server">
    
            <div>
    
                <asp:DropDownList ID="lbAllSongs" runat="server" AutoPostBack="true"></asp:DropDownList> <asp:Label ID="lblSelectedSong" runat="server"></asp:Label>
    
     
    
                <br />
    
                <audio id="audioPlayer" autoplay src="<%=SongToPlay %>" controls="true" onended="audioPlayerOnEnded()">Your browser does not support the
    
                <code>audio</code> element.</audio>
    
            </div>
    
        </form>
    
    </body>

    Code Behind:

    Public SongToPlay As String
    
     
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            If Not IsPostBack Then
    
                Dim pathLocal As String
    
                Dim pathSongs As String
    
                pathLocal = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ServerVariables("PATH"))
    
                pathSongs = pathLocal & "\Songs"
    
                Dim MyFile, MyPath As String
    
                MyPath = pathSongs
    
                MyFile = FileSystem.Dir(pathSongs & "\*.mp3")
    
     
    
                While MyFile <> ""
    
                    lbAllSongs.Items.Add(MyFile)
    
                    MyFile = FileSystem.Dir()
    
                End While
    
     
    
                lbAllSongs.SelectedIndex = 0
    
                SongToPlay = "Songs/" & lbAllSongs.SelectedItem.Text
    
            Else
    
     
    
                If Request.Form("__EVENTTARGET") = "audioPlayer" Then
    
                    audioPlayerOnEnded()
    
                Else
    
                    lblSelectedSong.Text = lbAllSongs.SelectedItem.Text
    
                    SongToPlay = "Songs/" & lbAllSongs.SelectedItem.Text
    
                End If
    
            End If
    
     
    
        End Sub
    
     
    
        Protected Sub btnSelectSong_Click(ByVal Source As Object, ByVal E As EventArgs)
    
        End Sub
    
     
    
        //This name is the same as the one in page but is works only in server side.
    
        Protected Sub audioPlayerOnEnded()
    
            Dim nextIndex As Integer = findNextIndex()
    
            lbAllSongs.SelectedIndex = nextIndex
    
            lblSelectedSong.Text = lbAllSongs.SelectedItem.Text
    
            SongToPlay = "Songs/" & lbAllSongs.SelectedItem.Text
    
        End Sub
    
     
    
        Private Function findNextIndex() As Integer
    
            Dim current As Integer = lbAllSongs.SelectedIndex
    
            Dim nextIndex As Integer
    
     
    
            If current + 1 > lbAllSongs.Items.Count - 1 Then
    
                nextIndex = 0
    
            Else
    
                nextIndex = current + 1
    
            End If
    
     
    
            Return nextIndex
    
        End Function

    Demo:

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 26, 2020 6:39 AM
  • User-1653812950 posted

    On my end, the code almost works that you posted. It automatically loads the next song into the Audio play, but the Player does not automatically play it. I still have to click the play button. It's really close. Thanks.

    Wednesday, February 26, 2020 9:57 PM
  • User-1330468790 posted

    Hi, qwsoftdraw,

     

    I think you are using the chrome as the browser to develop. However, Google changes chrome's autoplay policies in April of 2018 in order to boost the user experience since users are prone to anger when they load a website and an advertisement blares at them at full volume. That is the reason why the chrome prevent websites from playing audio unless user interacts with them. 

    More details about Chrome AutoPlay Policies, click:

    https://developers.google.com/web/updates/2017/09/autoplay-policy-changes 

    So, the solution is to add a control to complete the user interaction. That way, the next song will be played automatically when the previous one is ended.  

    Or, simply click the play button which is not recommended since it is not friendly for user experience.



    Regarding the problem that you said: 

    "It automatically loads the next song into the Audio play, but the Player does not automatically play it. I still have to click the play button". 

    The first suggestion is to make sure you have set the attribute "autoplay" in the audio tag. 

    If it still is not working, could you please provide me with the browser's version? It would be helpful to reproduce the problem from my side.

     

    Update Code (Focus on contents in yellow background):

    .aspx Page:

    <head runat="server">
    
        <title></title>
    
        <script type="text/javascript">
    
            function audioPlayerOnEnded() {
    
                javascript: __doPostBack('audioPlayer', '');
    
            }
    
     
    
            function autoPlay() {
    
                var audio = document.getElementById("audioPlayer");
    
                console.log(audio);
    
                audio.play();
    
            }
    
        </script>
    
    </head>
    
    <body>
    
        <form id="form1" runat="server">
    
            <div>
    
                <asp:DropDownList ID="lbAllSongs" runat="server" AutoPostBack="true"></asp:DropDownList> <asp:Label ID="lblSelectedSong" runat="server"></asp:Label>
    
     
    
                <br />
    
                <audio id="audioPlayer" autoplay src="<%=SongToPlay %>" controls="true" onended="audioPlayerOnEnded()">Your browser does not support the
    
                <code>audio</code> element.</audio>
    
                <input type="button" id="activeAutoPlayBtn" value="Start Auto Play" onclick="autoPlay()" />
    
            </div>
    
        </form>
    
    </body>

    Demo:

    Best regards,

    Sean

    Thursday, February 27, 2020 5:09 AM
  • User-1653812950 posted

    Thank you for your time and attention this. I am using Mozilla Firefox 72.0.1 (64-bit).

    I understand how annoying it could be to the general public to have music playing continuously in the background, but this whole project is for my own personal use. I can play songs from my electronic devices to my car radio via bluetooth and want to have my own musical selection on a website that I can play while driving.

    I personally tried many times to load a Windows Media player onto a webpage but could never get the player to show. I have tried to do a lot of research about the <audio> tag, and there is definitely a lot of interest in this feature on the internet, but the majority of it is in Javascript or C#, etc. Not vbscript, thus the initial post.

    Thanks again for your help.

    Thursday, February 27, 2020 8:34 PM
  • User-1330468790 posted

    Hi, qwsoftdraw,

     

    I tried the code on the firefox browser 72.0.1 and reproduced the problem. 

    After checking the settings of the firefoxI found that the reason why 'autoplay' is not working in your side is that the firefox browser blocks the autoplay by default.

     

    If you want to change this setting, you could follow the steps as below:

    1.Click the open menu on the top right corner of the browser and Choose 'Privacy Protection';

    2. Click into 'Manage Settings';

    3. Scroll down to 'Permissions' Section and choose the settings of 'AutoPlay;

    4. Set Default for all websites: 'Allow Audio and Video'; Or you can set for special websites.

    I checked for the previous code again and the problem has gone.

     

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 28, 2020 9:41 AM
  • User-1653812950 posted

    Sean,

    Thank you for all your help. Changing the settings in Mozilla Firefox did the trick. I did not need to use one of the last post about the INPUT button with autoplay. Everything else works great! Thanks again.

    Byron

    Friday, February 28, 2020 3:27 PM