mke*_*erz 0 java vaadin html5-audio vaadin14
我想在使用开发的其中一个应用中播放声音(.wav,作为byte [])Vaadin 14。不幸的是,我没有找到该用例的组件。
提供了Vaadin 8 Audio(https://vaadin.com/api/framework/8.5.2/com/vaadin/ui/Audio.html),但Vaadin 14中不提供。
我认为有一种解决方案,只需使用HTML <audio>并导入它即可。
<body>
<audio src="test.wav" controls autoplay loop>
</audio>
</body>
Run Code Online (Sandbox Code Playgroud)
是否还有“ Vaadin 14”解决方案?
As we mentioned in comments, there is no out-of-the-box component in V14, but it's quite easy to make an own one as described here : Creating a Simple Component Using the Element API :)
So I've checked it briefly and this seems to work:
AudioPlayer.java
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Tag;
@Tag("audio")
public class AudioPlayer extends Component {
public AudioPlayer(){
getElement().setAttribute("controls",true);
}
public void setSource(String path){
getElement().setProperty("src",path);
}
}
Run Code Online (Sandbox Code Playgroud)
Using:
AudioPlayer player=new AudioPlayer();
player.setSource("https://file-examples.com/wp-content/uploads/2017/11/file_example_WAV_1MG.wav");
add(player);
Run Code Online (Sandbox Code Playgroud)
I don't have any music file locally, so taken some random one from internet and passed as a source. That's, of course, not a bulletproof solution, just a proof of concept : )
我想为那些可能使用流的人添加一个简短的补充anasmi的好答案。
Anasmi 的 AudioPlayer.java:
public void setSource(final AbstractStreamResource resource) {
getElement().setAttribute("src", resource);
}
Run Code Online (Sandbox Code Playgroud)
要使其工作,您必须为流设置内容类型:
var stream = new StreamResource("foo", () -> {
byte[] data = getBytesFromFileMP3(soundfile);
return new ByteArrayInputStream(data); })
.setContentType("audio/mpeg"); // For MP3
Run Code Online (Sandbox Code Playgroud)