How to play an audio file or short sound on mobile device?

Hi CUBA team,
I’m investigating whether I could use CUBA Platform (V7.2.9) for a browser-app on a mobile device with a barcode scanner. Because I have no access to the scanner-engine I want to give feedback after a scan via a sound. This is: “OK-sound” when barcode is “good”, “error-sound” otherwise.
A scan just is like entering text in a Textfield and pressing ENTER and then catching the “EnterPressEvent” of that field.

So I want to play an audio file in the code of the “EnterPressEvent”
The only way I found to play a sound was to use a browser frame with a to an .mp3 sound file. Like this:



Basically this worked when I called
browerFrame.SetVisible(true)
But it worked only for the first “EnterPressEvent”. On second or third event, no sound was played.

My question: how do I get the sound at each event or are there even better ways to play a short sound file?

Thanks in advance

Alfred

Hello,

take a look at com.vaadin.ui.Audio component. It is based on HTML5 <audio> element and can play audio using Resource API (i.e. URL, Classpath, etc). For instance:

protected Audio audio;

@Subscribe
public void onInit(InitEvent event) throws MalformedURLException {
    audio = new Audio();
    audio.setShowControls(false);

    String path = "VAADIN/ok_sound.mp3";
    URL context = new URL(ControllerUtils.getLocationWithoutParams()); // or any other URL
    audio.setSource(new ExternalResource(new URL(context, path)));

    getWindow().unwrap(AbstractOrderedLayout.class).addComponent(audio);
}

@Subscribe("textField")
public void onTextFieldEnterPress(TextInputField.EnterPressEvent event) {
    audio.play();
}

File ok_sound.mp3 is placed in the WEB module web/VAADIN folder.
Unfortunately, I cannot find any stop() method, but If the audio is short I think it will be ok.

Another way is to create JsComponent. Here you can add <audio> element and play it.

Hello Roman,

your solution is exacty what I was looking for and works perfectly.
Thank you very much.

Alfred

1 Like