I want to play.mp3 files in Vaadin 14. This is my audio player.
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);
But when I try to play.mp3 files, nothing happens. What have I missed? Do I need to convert.mp3 files to.wav before? How can I do that just temporary. I'm not planning to save any.wav files on the computer, because I already have.mp3 files stored.
Your approach should work, I just create a PR to the Vaadin cookbook with a recipe for this.
Note that the browser needs to be able to access the audio file through that same path. If you set the src
to audio/mysong.mp3
, then you should be able to open it in the browser also as eg localhost:8080/audio/mysong.mp3
(or the equivalent URL for your setup).
Take a look at the ways of importing in Vaadin to see where to put your file, in particular the Resource Cheat Sheet for static files.
Edit:
I'm not sure why your files don't work on the first try, but I could reproduce it in your project, also with my own mp3 files. You can see an error 416 in the console, something to do with a mismatch in the range of bytes requested.
I found a workaround that you could try (you might want to move your audio to just src/main/resources
for this, and/or update the AudioPlayer
to accept an 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.