如何在Vaadin Audio组件中定位播放位置或读取当前播放时间?
Working with Playback Position & Current Time in Vaadin Audio Component
Absolutely! You can definitely both seek to a specific playback position and read the current playback time of Vaadin's Audio component. The solution leverages the underlying HTML5 <audio> element API that Vaadin's component wraps. Here's a step-by-step breakdown:
1. Read Current Playback Time
To get the current time (in seconds) that the audio is playing at, access the currentTime property of the component's underlying DOM element:
// Initialize your Audio component Audio audio = new Audio(new FileResource(new File("your-audio-file.mp3"))); // Fetch current playback time double currentPlaybackTime = audio.getElement().getProperty("currentTime"); System.out.println("Current time: " + currentPlaybackTime + " seconds");
2. Seek to a Specific Playback Position
To jump directly to a desired time point (also in seconds), set the same currentTime property with your target value:
// Jump to the 25-second mark audio.getElement().setProperty("currentTime", 25.0);
Key Notes for Reliability
- Wait for Audio to Load: Setting
currentTimebefore the audio has finished loading might not work. Listen for thecanplayevent to ensure the audio is ready:audio.getElement().addEventListener("canplay", event -> { // Safe to set playback position now audio.getElement().setProperty("currentTime", 10.0); }); - Real-Time Time Updates: If you need to track time changes continuously (e.g., for a progress bar), listen to the
timeupdateevent, which fires as the playback time changes:audio.getElement().addEventListener("timeupdate", event -> { double updatedTime = audio.getElement().getProperty("currentTime"); // Update your UI or process the time value here });
内容的提问来源于stack exchange,提问作者Igor Vurdelja
相关产品推荐
相关产品推荐

