Search code examples
javavaadinhtml5-audiovaadin14

How to play sound in Vaadin 14?


I want to play sound (.wav, as byte[]) in one of my apps I develop using Vaadin 14. Unfortunately I did not find a component for this use case.

Vaadin 8 offered Audio (https://vaadin.com/api/framework/8.5.2/com/vaadin/ui/Audio.html) but it is not available in Vaadin 14.

I think there is a solution by simply using HTML <audio> and import this.

<body>
  <audio src="test.wav" controls autoplay loop>
    </audio>
</body>

Is there also a "Vaadin 14"-solution for this?


Solution

  • 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);
        }
    }
    
    

    Using:

    AudioPlayer player=new AudioPlayer();
    player.setSource("https://file-examples.com/wp-content/uploads/2017/11/file_example_WAV_1MG.wav");
    add(player);
    

    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 : )