简体   繁体   English

如何在Vaadin 14中播放.mp3文件

[英]How to play .mp3 files in Vaadin 14

I want to play.mp3 files in Vaadin 14. This is my audio player.我想在 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);

But when I try to play.mp3 files, nothing happens.但是当我尝试播放 .mp3 文件时,没有任何反应。 What have I missed?我错过了什么? Do I need to convert.mp3 files to.wav before?我之前需要将.mp3 文件转换为.wav 吗? 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.我不打算在计算机上保存任何.wav 文件,因为我已经存储了.mp3 文件。

Your approach should work, I just create a PR to the Vaadin cookbook with a recipe for this.您的方法应该有效,我只是为 Vaadin 食谱创建了一个 PR,其中包含一个食谱。

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).如果您将src设置为audio/mysong.mp3 ,那么您应该也可以在浏览器中打开它,例如localhost:8080/audio/mysong.mp3 (或等效的 URL 用于您的设置)。

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.看看在 Vaadin 中导入的方法,看看将文件放在哪里,特别是 static 文件的资源备忘单。

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.我不确定为什么你的文件在第一次尝试时不起作用,但我可以在你的项目中重现它,也可以使用我自己的 mp3 文件。 You can see an error 416 in the console, something to do with a mismatch in the range of bytes requested.您可以在控制台中看到错误 416,这与请求的字节范围不匹配有关。

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 ):我找到了一个您可以尝试的解决方法(您可能想为此将音频移动到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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM