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 e.g. 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);
}
Related
I am usinf the JavaFx method of playing music files but it isn't working (sound not playing). I feel the problem lies in my files location. Where do I put the .mp3 in my java projects folder for it to be referenced with a simple string as so? Or is there another way to reference it? JavaFX Media takes a String parameter.
String test = "test.mp3";
Media x = new Media(test);
MediaPlayer mediaPlayer = new MediaPlayer(x);
mediaPlayer.play();
If you have read the JavaDoc of Media, then you know that you have to give a http, file or jar URI to the constructor you are using.
Actually from looking at the source code I wonder that you are not getting an IllegalArgumentException.
However, use Class.getResource(...).toURI().toString() to get the String you want to give to the Media constructor.
The combination of which Class object you call this on and what you give to the getResource() method depends on how you layout your files.
If you have your file besides your class, getClass().getResource("file.name") should work.
If you have your file in the root of your classpath, getClass().getResource("/file.name") should do.
You can give any other valid http, file or jar URI to the contructor too of course.
I manage to make a program that could understand mp3 in Java (by jaco.mp3 jar) and it works. However this means that the .Wav files doesn't work of course. So I fixed so that I could use the Wav but the problem will then be that I can't use the mp3 then. so I found out that I could use the File Extension and my idea was to make like this:
If the last 3 or 4 letters ends with .mp3 then do the mp3 method, if its .Wav then to Wave method. but I don't really know how to manage it together, I was thinking more like a Switch-statement. But I really never worked with File extension before and could need som help with that!
However this is my mp3 method that is like this right now:
public void Choose() {
String userDir = System.getProperty("user.home");
JFileChooser fileChooser = new JFileChooser(userDir +"/Desktop");
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());
mp3_player = new MP3Player(selectedFile);
lblPlayURL.setText(selectedFile.getName());
}
}
}
as you can see I have a JFileChooser where I pick the song I want of course and I still want to do it, only that the different is now it should work both as .Wav and .mp3. But I don't really know how to go further with it. so any help is needed from you guys! :)
Before people is trying to give any suggestions from a thread that says Playing .Wav and .Mp3. I would just say first that I have read it and there is only answers about each of them, Only mp3 or the .Wav. not both. so thats why I created this thread because I need help!
You can perhaps check if the file path ends with MP3 or WAV and have an if statement to run different programs depending on the condition.
This can be done like so:
String ext = selectedFile.getPath();
if(ext.endsWith(".wav"))
{
// A WAV file was chosen
}
else if(ext.endsWith(".mp3"))
{
// An MP3 file was chosen
}
else
{
// Something else was chosen
}
EDIT: This method together with Bogdan's answer is probably your best bet.
Add FileFilter rules to your JFileChooser to match .mp3 and .wav files:
fileChooser.addChoosableFileFilter(new FileTypeFilter(".mp3", "MP3 Files"));
fileChooser.addChoosableFileFilter(new FileTypeFilter(".wav", "WAV files"));
How to add file filter for JFileChooser dialog.
So this is what I want to do. I want to load an .wav music file from my project folder. I have done this with a image, as displayed below. I want to do this with an audio file. Is this possible? Is there an easy way to convert my old method to a new one. The reason I want to do this is because I want to have all the files for my program in a .jar file so I can just send that and it plays.
static audiotest music = new audiotest( "C:\\WINDOWS\\Media\\POL-purple-hills-short.wav" );
music.start();
URL mountainImage2 = Main.class.getResource("Mountains.png");
mountainImage = ImageIO.read(mountainImage2);
I'm trying to make a website using the Play! Framework (v2.2.0 & in Java) that keeps homework in a repository for students to browse. I want to allow students to upload .doc/.docx files to the server and have the files get automatically converted to .html upon upload.
Here's my code for the HomeworkSnippet data type, for reference:
#SuppressWarnings("serial")
#Entity
public class HomeworkSnippet extends Model {
public HomeworkSnippet (String filepath) {
this.filepath = filepath;
this.snippetRender = snippet.render(/*code for html version of file at filepath here*/);
}
public static Finder<Long,HomeworkSnippet> find = new Finder<Long,HomeworkSnippet>(
Long.class, HomeworkSnippet.class
);
#Id
public Long id;
public String filepath;
public Html snippetRender;
}
Now the way I would like to do this is by using the JODConverter tool that allows you to convert .docx to .html explicitly using OpenOffice.org or LibreOffice. However, how should I do this when JODConverter SEEMS to need a warfile when Play! Framework doesn't use warfiles. I'm a little out of my depth, please forgive me if this makes no sense.
You can download the jar file also. If you go to a download page for the project, such as this:
http://sourceforge.net/projects/jodconverter/files/JODConverter/2.2.2/
You'll be given the opportunity to download a tomcat zip, a webapp zip, or the .. other zip, that is just the name of the library: jodconverter-2.2.2.zip. Download that one, and include it as a Play library. Fun project! Enjoy!
i want to ask you regardless finding the file path...
I have, or i would have files that will be associated with my app, but i dont know how to find out the file path that initializes opening my app.
For example:
If i click in windows enviroment on excel file "file.xlx", windows will open excel application with this file "file.xls" and i want exactly the same. After my app will be open, i want to know file path that inicializes my app to start...
I hope that my question is understandable and i apologize for my bad english.. :)
Edit:
I try add some another example...
I try describe some logic operations...
1 - nothing is running, only windows - i hope :)
2 - user click on some file that is somewhere in the HDD ( this file can have different name and different location )
3 - this file with some extension has associated start with my app
4 - app automatically find out on whitch file user clicked ( who invoke the launch of my application ) and use this file path on other work...
I think that should be something like when i start console app. with some argument....but this argument i must get from some windows location.
Just like when i click on file.txt and windows will open notepad and notepad will have automatically open this file.txt, or i click on file.dbf and windows will open the foxpro with this file
I want click on file.xxx and my app will open and work with this file automatically, so there i think must be some way how to get this file location on which i clicked...
I hope this help...
Look at the java system properties http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html, you probably want user.dir
i think what you need is a program like this , this will calculate the existance of your file in side the given directory
package fileSearch;
import java.io.File;
import java.io.FilenameFilter;
public class fileSearch {
/**
* #param args
*/
public static void main(String[] args) {
fileSearch obj = new fileSearch();
obj.finder("program.txt");
for(int i=0;i<obj.finder("C:/Users/hussain.a/Desktop").length;i++)
{
System.out.println(obj.finder("C:/Users/hussain.a/Desktop")[i].getName());
}
}
public File[] finder( String dirName){
File dir = new File(dirName);
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename)
{ return filename.endsWith(".txt"); }
} );
}
}
now its up to you to apply to your desired directory , if you want it to exactly like the windows program , then you will have to use root directory every time and pass the file name as a parameter replacing ".txt" in this program
hope it serves , rest is up to you to implement it
I think you can set the os,like the registry,when you installing the app.
String osName = System.getProperty("os.name") ;