我在组件中使用音频标签,如下所示:https://cookbook.vaadin.com/embed-audio
现在我想在音频播放时触发一个事件。我发现音频标签提供了 timeupdate 事件。我能抓住它,而且效果很好。但现在我想获取音频播放的当前时间。我读到音频元素有一个属性currentTime。但是当我想从音频元素获取该属性时,它不存在。
我打印了音频的所有属性,每个获取的属性都是src和style。希望你能在这里为我指出正确的方向,因为这对我来说绝对没有意义。
编辑:当我通过executeJs查询属性时,例如:
UI.getCurrent().getPage().executeJs("return $0.currentTime", audio.getElement());
...,我得到了我正在寻找的值,但是事件侦听器不再同步工作。
我的班级是这样的:
@Tag("audio")
public class Audio extends Component implements HasSize {
private static final long serialVersionUID = 1L;
private static final PropertyDescriptor<String, String> srcDescriptor = PropertyDescriptors
.attributeWithDefault("src", "");
public Audio() {
super();
getElement().setProperty("controls", true);
}
public Audio(String src) {
setSrc(src);
getElement().setProperty("controls", true);
}
public String getSrc() {
return get(srcDescriptor);
}
public void setSrc(String src) {
set(srcDescriptor, src);
}
public void setSrc(final AbstractStreamResource resource) {
getElement().setAttribute("src", resource);
}
public void play() {
getElement().callJsFunction("play");
}
public void stop() {
getElement().callJsFunction("stop");
}
@DomEvent("timeupdate")
public static class TimeUpdateEvent extends ComponentEvent<Audio> {
private final int progress;
public TimeUpdateEvent(Audio audio, boolean fromClient) {
super(audio, fromClient);
String currentTime = audio.getElement().getAttribute("currentTime");
this.progress = Integer.valueOf(currentTime);
}
public Audio getAudio() {
return (Audio) this.source;
}
public int getProgress() {
return this.progress;
}
}
public Registration addTimeUpdateListener(ComponentEventListener<Audio.TimeUpdateEvent> listener) {
return addListener(Audio.TimeUpdateEvent.class, listener);
}
}
好吧,我找到了一种使用属性机会侦听器的方法。我正在观察 javascript 属性 currentTime 并对 timeupdate 事件做出反应。这不会发出 ComponentEvent 但我可以接受。
public Audio() {
super();
this.getElement().addPropertyChangeListener("currentTime", "timeupdate", e -> {
currentTime = Float.parseFloat(e.getValue().toString());
});
getElement().setProperty("controls", true);
}