This question already has answers here:
How to have the user choose an audio file and play it in Java
(2 answers)
Closed 9 years ago.
I've got a problem with this Code..
I tried to play some sound, which is in the Musik directory in Eclipse. I already tested, if the sound exist, can be read, and can be opened. All looks ok. But I can't hear anything.
package mhm;
import java.applet.Applet;
import java.applet.AudioClip;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
new Main();
}
URL url = null;
AudioClip clip;
File file = new File("Musik/VOWZN-UnRational.wav");
public Main() {
try {
url = new URL("file://" + file.getPath());
} catch (MalformedURLException e) {
e.printStackTrace();
}
clip = Applet.newAudioClip(url);
clip.play();
new Menu();
}
}
On Runtime, there aren't any errors..
That code should not work in an (untrusted) applet. It is trying to access a file in the local filesystem (via a "file:" URL), and sandbox security should block that.
Related
I need to write a Java program that opens a PDF file at a named destination. The file test.pdf contains the named destination "DestinationX" on page 2. The program opens the PDF file but does not go to the named destination. How do I get to the named destination?
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class MyLauncher {
static void openFileAtNamedDest(){
if (Desktop.isDesktopSupported()) {
try {
URI myURI = new URI("file:///C:/test.pdf#nameddest=DestinationX");
Desktop.getDesktop().browse( myURI );
} catch (IOException e) {
e.printStackTrace();
}
catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
openFileAtNamedDest();
}
}
According to the spec, the format of your URL is correct. The only question is what application you are actually launching via browse(). I think it acts the same way as if you had double-clicked the file's icon on your desktop: it will launch whatever application is registered as the default handler for PDFs.
Acrobat should be able to handle a URL with a named destination, but other PDF viewers may not support it.
I am trying to play a song (mp3 file) in java. I have been looking around for a few hours now and none of the ways I found worked properly.
public void play()
{
String song = "song.mp3";
Media track = new Media(song);
MediaPlayer mediaPlayer = new MediaPlayer(track);
mediaPlayer.play();
}
I have tried doing that but it gives me errors.
I have imported JMF and JLayer.
I have also read other questions that are like this one on this forum and none of them have helped me.
I just need a hand to help play an mp3 file.
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
}catch(Exception e){System.out.println(e);}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
For this you'll need to install Java Media Framework (JMF) in your PC. One you have it installed,then try this piece of code:
import javax.media.*;
import java.net.*;
import java.io.*;
import java.util.*;
class AudioPlay
{
public static void main(String args[]) throws Exception
{
// Take the path of the audio file from command line
File f=new File("song.mp3");
// Create a Player object that realizes the audio
final Player p=Manager.createRealizedPlayer(f.toURI().toURL());
// Start the music
p.start();
// Create a Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);
// Read a line and store it in st
String st=s.nextLine();
// If user types 's', stop the audio
if(st.equals("s"))
{
p.stop();
}
}
}
You may run into unable to handle formaterror, that is because Java took out the MP3 support by default (pirate copyright issue), you are required to install a “JMF MP3 plugin” in order to play MP3 file.
Go Java’s JMF website to download it
http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html
To be sure that you are using a supported format file, check here:
http://www.oracle.com/technetwork/java/javase/formats-138492.html
If you are using windows7, you may have to read this as well:
https://forums.oracle.com/forums/thread.jspa?threadID=2132405&tstart=45
How about JavaFX application-
import java.net.URL;
import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class VLC extends Application {
void playMedia() {
String mp3 = "00- Tu Hi Mera.mp3";
URL resource = getClass().getResource(mp3);
System.out.println(resource.toString());
Media media = new Media(resource.toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
public static void main(String args[]) {
new VLC().playMedia();
}
#Override
public void start(Stage stage) throws Exception {
}
}
Im using Windows 7 and can "Java Platform SE Binary" in my sound mixer but yet still no sound seems to play.
My code is:
import javax.media.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLExc;
public class SimpleAudioPlayer {
private Player audioPlayer = null;
public SimpleAudioPlayer(URL url) throws IOException, NoPlayerException,
CannotRealizeException {
audioPlayer = Manager.createRealizedPlayer(url);
}
public SimpleAudioPlayer(File file) throws IOException, NoPlayerException,
CannotRealizeException {
this(file.toURL());
}
public void play() {
audioPlayer.start();
}
public void stop() {
audioPlayer.stop();
audioPlayer.close();
}
public static void main(String[] args) {
try{
File audioFile = new File("/t.mp3");
SimpleAudioPlayer player = new SimpleAudioPlayer(audioFile);
System.out.println();
System.out.println("-> Playing file '" +
audioFile.getAbsolutePath() + "'");
System.out.println(" Press the Enter key to exit");
player.play();
// wait for the user to press Enter to proceed.
System.in.read();
System.out.println("-> Exiting");
player.stop();
}catch(Exception ex){
ex.printStackTrace();
}
System.exit(0);
}
}
I use the Windows Preformance JMF edition. The MP3 im trying to play works fine in VLC/WMP so it cant be the file.
The code also throws no exceptions or error when running, it just doesnt seem to play the sound.
Is there something im missing? Like pulling the sound card? E.g. taking over it so i can play sound out of it?
Im overall aim is to to a MP3 streaming service using RTP/RTSP so any links,advice or tuturiols would be help as im currelnt using IBM JMF Tuturiol and Java Demo
Please ask if any more information is needed!
UPDATE-
Downloaded WAV FILE and it seemed to play, how can i make MP3s play?
Added formats and tried this code and still the same issue:
import java.io.File;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;
public class SimpleAudioPlayer {
public static void main(String[] args) {
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1, input2},
new Format[]{output},
PlugInManager.CODEC
);
try {
Player player = Manager.createPlayer(new MediaLocator(new File("/t.mp3").toURI().toURL()));
player.start();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
Unable to handle format: mpeglayer3, 44100.0 Hz, 16-bit, Stereo, LittleEndian, Signed, 16000.0 frame rate, FrameSize=32768 bits
Failed to realize: com.sun.media.PlaybackEngine#62deaa2e
Error: Unable to realize com.sun.media.PlaybackEngine#62deaa2e
Thats the error!
As I thought, it's a missing codec.
I think this is what you need: http://www.oracle.com/technetwork/java/javase/download-137625.html
I am working on a concept of a filesystem for a program. I am writing in Java (using JDK 7 u17).
To get started I built off of some tutorial that were showing my how to create a zip based filesystem using the FileSystemProvider class.
When I execute the code I have it do similar task to the examples which is copy a text file from the my desktop and place it in the zip file. The problem is once it copies the file it does not write it into the zip file, it seems to leave the file in memory which is destroyed when the program is terminated.
The problem is I cannot understand why, as far as I can tell everything looks to be in order but something is clearly not!
Oh yeah the same thing goes for directories too. If I tell the filesystem to make a new directory it just creates it in memory and there is nothing in the zip file.
Anyhow here is my working code;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class Start {
public static void main(String[] args) {
Map <String, String> env = new HashMap<>();
env.put("create", "true");
env.put("encoding", "UTF-8");
FileSystem fs = null;
try {
fs = FileSystems.newFileSystem(URI.create("jar:file:/Users/Ian/Desktop/test.zip"), env);
} catch (IOException e) {
e.printStackTrace();
}
Path externalTxtFile = Paths.get("/Users/Ian/Desktop/example.txt");
Path pathInZipFile = fs.getPath("/example.txt");
try {
Files.createDirectory(fs.getPath("/SomeDirectory"));
} catch (IOException e) {
e.printStackTrace();
}
if (Files.exists(fs.getPath("/SomeDirectory"))) {
System.out.println("Yes the directory exists in memory.");
} else {
System.out.println("What directory?");
}
// Why is the file only being copied into memory and not written out the jar/zip archive?
try {
Files.copy(externalTxtFile, pathInZipFile);
} catch (IOException e) {
e.printStackTrace();
}
// The file clearly exists just before the program ends, what is going on?
if (Files.exists(fs.getPath("/example.txt"))) {
System.out.println("Yes the file has been copied into memory.");
} else {
System.out.println("What file?");
}
}
}
I just want to add something.
Perhaps the example that you found was incomplete (I can not check since you do not references it) but in all examples I found the FileSystem instance is closed properly.
The FileSystem abstract class implements Closeable, so the close() method is called (automatically) leaving the try in the following code:
try (final FileSystem fs = FileSystems.newFileSystem(theUri, env)) {
/* ... do everything you want here ; do not need to call fs.close() ... */
}
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
I have this code :
package test;
import java.io.File;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;
public class AudioTest {
public static void main(String[] args) {
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1, input2},
new Format[]{output},
PlugInManager.CODEC
);
try{
Player player = Manager.createPlayer(new MediaLocator(new File("1.mp3").toURI().toURL()));
player.realize();
player.start();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
i'm trying to play an mp3 file, mp3plugin is added to the project lib as well as the jmf jar.
there's no error on the console but cant hear a sound.
the file is not playing.
.wav files are playing fine.
any idea ?
JMF is a bad option. The project was abandoned long time ago.
I have answered a similar question here:
Java - Error when trying to use mp3plugin for playing an mp3 file
it might be usefull for you - Im using Java Sound
The following is all I need to play music.
public static void main(String args[]) throws NoPlayerException, CannotRealizeException, IOException {
MediaLocator ml = new MediaLocator((new File("roar_of_future.mp3").toURL()));
Player player = Manager.createRealizedPlayer(ml);
player.start();
}
So please make sure mp3plugin.jar is in the classpath and your javasdk is Java 8 (32bit) or 7 (32bit) because JMF is not working on Java 9 and above.