You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Excel VBA的Selenium EdgeDriver检测HTML音频播放结束

Solution for Auto-Closing Edge After Audio Ends in VBA Selenium

To automatically close the Edge browser once the audio finishes playing, you can use Selenium's ExecuteAsyncScript method to inject JavaScript that listens for the HTML5 audio ended event. Here's how to implement this in your VBA code:

Step-by-Step Implementation

  1. Wait for the Audio Element to Be Available
    First, ensure the audio element has loaded on the page before attaching the event listener to avoid runtime errors:

    driver.WaitUntil _
        Condition:=Function(d) d.FindElementByTag("audio").IsDisplayed, _
        Timeout:=10000 ' Wait up to 10 seconds
    
  2. Inject Async JavaScript to Listen for the 'ended' Event
    Use ExecuteAsyncScript to run a script that attaches an event listener to the audio element. The script will call Selenium's built-in callback once the audio ends, which signals VBA to proceed:

    driver.ExecuteAsyncScript _
        "var audio = document.querySelector('audio');" & _
        "audio.addEventListener('ended', function() {" & _
            "arguments[0](); // Notify Selenium the event has fired" & _
        "});"
    
    • If your page has multiple audio elements, replace document.querySelector('audio') with a more specific selector (e.g., document.getElementById('target-audio-id') or document.querySelector('.audio-player-class')).
  3. Close the Browser
    Once the async script completes (when the audio ends), call Quit to close Edge:

    driver.Quit
    

Full Example Code

Integrate the above into your existing workflow:

Sub AutoCloseAfterAudio()
    Dim driver As New EdgeDriver
    
    ' Initialize Edge and navigate to your audio page
    driver.Get "https://your-audio-page-url.com"
    
    ' Optional: Trigger playback if audio doesn't start automatically
    driver.FindElementByTag("audio").Click
    
    ' Wait for audio element to load
    driver.WaitUntil _
        Condition:=Function(d) d.FindElementByTag("audio").IsDisplayed, _
        Timeout:=10000
    
    ' Wait for audio playback to finish
    driver.ExecuteAsyncScript _
        "var audio = document.querySelector('audio');" & _
        "audio.addEventListener('ended', function() {" & _
            "arguments[0]();" & _
        "});"
    
    ' Close the browser
    driver.Quit
End Sub

Notes

  • Timeout Handling: Add driver.SetAsyncScriptTimeout 30000 (30 seconds) before ExecuteAsyncScript to set a maximum wait time if you want to avoid infinite waits.
  • Selector Precision: Always use the most specific selector possible to target the correct audio element on your page.

内容的提问来源于stack exchange,提问作者김수연

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:27:46