问题描述
我想在Vaadin 14中播放.mp3文件。这是我的音频播放器。
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Tag;
@Tag("audio")
public class AudioPlayer extends Component {
/**
*
*/
private static final long serialVersionUID = 1L;
public AudioPlayer(){
getElement().setAttribute("controls",true);
}
public void setSource(String path){
getElement().setProperty("src",path);
}
}
AudioPlayer player = new AudioPlayer();
player.setSource("music/my music file.mp3");
add(player);
但是当我尝试播放.mp3文件时,没有任何反应。我错过了什么? 我需要先将.mp3文件转换为.wav吗?我该怎么做只是暂时的。 我不打算在计算机上保存任何.wav文件,因为我已经存储了.mp3文件。
解决方法
您的方法应该行得通,我为此创建了一个a PR to the Vaadin cookbook配方。
请注意,浏览器需要能够通过同一路径访问音频文件。如果您将src
设置为audio/mysong.mp3
,那么您也应该可以在浏览器中将其打开,例如localhost:8080/audio/mysong.mp3
(或您设置的等效URL)。
看看the ways of importing in Vaadin,了解文件的存放位置,尤其是静态文件的资源备忘单。
编辑:
我不确定为什么您的文件在第一次尝试时不起作用,但是我可以在您的项目中复制它,也可以使用自己的mp3文件。您会在控制台中看到错误416,这与请求的字节范围不匹配有关。
我找到了一个可解决的方法,您可以尝试(为此,您可能希望将音频移至src/main/resources
,和/或更新AudioPlayer
以接受AbstractStreamResource
):
if(!reverseTranslation.getValue()) {
frenchSentence.setValue(sentenceInFrench);
String audioPath = "/META-INF/resources/audio/" + sentenceInFrench + ".mp3";
AbstractStreamResource resource =
new StreamResource(sentenceInFrench,() -> getClass().getResourceAsStream(audioPath));
player.getElement().setAttribute("src",resource);
}