Audio file in java

Java — reading, manipulating and writing WAV files

In a Java program, what is the best way to read an audio file (WAV file) to an array of numbers ( float[] , short[] , . ), and to write a WAV file from an array of numbers?

9 Answers 9

I read WAV files via an AudioInputStream . The following snippet from the Java Sound Tutorials works well.

int totalFramesRead = 0; File fileIn = new File(somePathName); // somePathName is a pre-existing string whose value was // based on a user selection. try < AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(fileIn); int bytesPerFrame = audioInputStream.getFormat().getFrameSize(); if (bytesPerFrame == AudioSystem.NOT_SPECIFIED) < // some audio formats may have unspecified frame size // in that case we may read any amount of bytes bytesPerFrame = 1; >// Set an arbitrary buffer size of 1024 frames. int numBytes = 1024 * bytesPerFrame; byte[] audioBytes = new byte[numBytes]; try < int numBytesRead = 0; int numFramesRead = 0; // Try to read numBytes bytes from the file. while ((numBytesRead = audioInputStream.read(audioBytes)) != -1) < // Calculate the number of frames actually read. numFramesRead = numBytesRead / bytesPerFrame; totalFramesRead += numFramesRead; // Here, do something useful with the audio data that's // now in the audioBytes array. >> catch (Exception ex) < // Handle the error. >> catch (Exception e) < // Handle the error. >

To write a WAV, I found that quite tricky. On the surface it seems like a circular problem, the command that writes relies on an AudioInputStream as a parameter.

Читайте также:  Vector in java with examples

But how do you write bytes to an AudioInputStream ? Shouldn’t there be an AudioOutputStream ?

What I found was that one can define an object that has access to the raw audio byte data to implement TargetDataLine .

This requires a lot of methods be implemented, but most can stay in dummy form as they are not required for writing data to a file. The key method to implement is read(byte[] buffer, int bufferoffset, int numberofbytestoread) .

As this method will probably be called multiple times, there should also be an instance variable that indicates how far through the data one has progressed, and update that as part of the above read method.

When you have implemented this method, then your object can be used in to create a new AudioInputStream which in turn can be used with:

AudioSystem.write(yourAudioInputStream, AudioFileFormat.WAV, yourFileDestination) 

As a reminder, an AudioInputStream can be created with a TargetDataLine as a source.

As to the direct manipulating the data, I have had good success acting on the data in the buffer in the innermost loop of the snippet example above, audioBytes .

While you are in that inner loop, you can convert the bytes to integers or floats and multiply a volume value (ranging from 0.0 to 1.0 ) and then convert them back to little endian bytes.

I believe since you have access to a series of samples in that buffer you can also engage various forms of DSP filtering algorithms at that stage. In my experience I have found that it is better to do volume changes directly on data in this buffer because then you can make the smallest possible increment: one delta per sample, minimizing the chance of clicks due to volume-induced discontinuities.

I find the «control lines» for volume provided by Java tend to situations where the jumps in volume will cause clicks, and I believe this is because the deltas are only implemented at the granularity of a single buffer read (often in the range of one change per 1024 samples) rather than dividing the change into smaller pieces and adding them one per sample. But I’m not privy to how the Volume Controls were implemented, so please take that conjecture with a grain of salt.

All and all, Java.Sound has been a real headache to figure out. I fault the Tutorial for not including an explicit example of writing a file directly from bytes. I fault the Tutorial for burying the best example of Play a File coding in the «How to Convert. » section. However, there’s a LOT of valuable FREE info in that tutorial.

I’ve since used the following code to write audio from a PCM file in my own projects. Instead of implementing TargetDataLine one can extend InputStream and use that as a parameter to the AudioSystem.write method.

public class StereoPcmInputStream extends InputStream < private float[] dataFrames; private int framesCounter; private int cursor; private int[] pcmOut = new int[2]; private int[] frameBytes = new int[4]; private int idx; private int framesToRead; public void setDataFrames(float[] dataFrames) < this.dataFrames = dataFrames; framesToRead = dataFrames.length / 2; >@Override public int read() throws IOException < while(available() >0) < idx &= 3; if (idx == 0) // set up next frame's worth of data < framesCounter++; // count elapsing frames // scale to 16 bits pcmOut[0] = (int)(dataFrames[cursor++] * Short.MAX_VALUE); pcmOut[1] = (int)(dataFrames[cursor++] * Short.MAX_VALUE); // output as unsigned bytes, in range [0..255] frameBytes[0] = (char)pcmOut[0]; frameBytes[1] = (char)(pcmOut[0] >> 8); frameBytes[2] = (char)pcmOut[1]; frameBytes[3] = (char)(pcmOut[1] >> 8); > return frameBytes[idx++]; > return -1; > @Override public int available() < // NOTE: not concurrency safe. // 1st half of sum: there are 4 reads available per frame to be read // 2nd half of sum: the # of bytes of the current frame that remain to be read return 4 * ((framesToRead - 1) - framesCounter) + (4 - (idx % 4)); >@Override public void reset() < cursor = 0; framesCounter = 0; idx = 0; >@Override public void close() < System.out.println( "StereoPcmInputStream stopped after reading frames:" + framesCounter); >> 

The source data to be exported here is in the form of stereo floats ranging from -1 to 1. The format of the resulting stream is 16-bit, stereo, little-endian.

I omitted skip and markSupported methods for my particular application. But it shouldn’t be difficult to add them if they are needed.

Источник

How can I play sound in Java?

I wrote the following code that works fine. But I think it only works with .wav format.

public static synchronized void playSound(final String url) < new Thread(new Runnable() < // The wrapper thread is unnecessary, unless it blocks on the // Clip finishing; see comments. public void run() < try < Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream( Main.class.getResourceAsStream("/path/to/sounds/" + url)); clip.open(inputStream); clip.start(); >catch (Exception e) < System.err.println(e.getMessage()); >> >).start(); > 

To avoid Clip being shut down at random time, a LineListener is required. Have a look: stackoverflow.com/questions/577724/trouble-playing-wav-in-java/…

+1 for a solution that uses the public API. Isn’t creating a new thread unnecessary(redundant) though?

Thanx.. Is it redundant? I made it into a new thread so I can play the sound again before the first clip ends.

1) The Thread is unnecessary. 2) For a good example of using Clip , see the JavaSound info. page. 3) If a method requires an URL (or File ) give it a dang URL (or File ) rather than accept a String that represents one. (Just a personal ‘bee in my bonnet’.) 4) e.printStackTrace(); provides more information with less typing than System.err.println(e.getMessage()); .

import sun.audio.*; //import the sun.audio package import java.io.*; //** add this into your application code as appropriate // Open an input stream to the audio file. InputStream in = new FileInputStream(Filename); // Create an AudioStream object from the input stream. AudioStream as = new AudioStream(in); // Use the static class member "player" from class AudioPlayer to play // clip. AudioPlayer.player.start(as); // Similarly, to stop the audio. AudioPlayer.player.stop(as); 

This example comes from a 1997 JavaWorld article. Way out of date, You should NOT use sun.* packages.

+1 for not using the sun.* packages. They have weird bugs like not handling files > 1MB and not being able to play one clip if the previous hasn’t finished yet, etc.

I didn’t want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).

private static void playSound(String sound) < // cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader(); URL file = cl.getResource(sound); final Media media = new Media(file.toString()); final MediaPlayer mediaPlayer = new MediaPlayer(media); mediaPlayer.play(); >

Notice : You need to initialize JavaFX. A quick way to do that, is to call the constructor of JFXPanel() once in your app :

For whatever reason, the top answer by wchargin was giving me a null pointer error when I was calling this.getClass().getResourceAsStream().

What worked for me was the following:

void playSound(String soundFile) < File f = new File("./" + soundFile); AudioInputStream audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL()); Clip clip = AudioSystem.getClip(); clip.open(audioIn); clip.start(); >

And I would play the sound with:

 playSound("sounds/effects/sheep1.wav"); 

sounds/effects/sheep1.wav was located in the base directory of my project in Eclipse (so not inside the src folder).

hello Anrew, your code worked for me, but i noticed that takes a little extra time in execution. about 1,5 sec.

getResourceAsStream() will return null if the resource is not found, or throw the exception if name is null — not a fault of top answer if the given path is not valid

For playing sound in java, you can refer to the following code.

import java.io.*; import java.net.URL; import javax.sound.sampled.*; import javax.swing.*; // To play sound using Clip, the process need to be alive. // Hence, we use a Swing application. public class SoundClipTest extends JFrame < public SoundClipTest() < this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("Test Sound Clip"); this.setSize(300, 200); this.setVisible(true); try < // Open an audio input stream. URL url = this.getClass().getClassLoader().getResource("gameover.wav"); AudioInputStream audioIn = AudioSystem.getAudioInputStream(url); // Get a sound clip resource. Clip clip = AudioSystem.getClip(); // Open audio clip and load samples from the audio input stream. clip.open(audioIn); clip.start(); >catch (UnsupportedAudioFileException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >catch (LineUnavailableException e) < e.printStackTrace(); >> public static void main(String[] args) < new SoundClipTest(); >> 

I created a game framework sometime ago to work on Android and Desktop, the desktop part that handle sound maybe can be used as inspiration to what you need.

Here is the code for reference.

package com.athanazio.jaga.desktop.sound; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; public class Sound < AudioInputStream in; AudioFormat decodedFormat; AudioInputStream din; AudioFormat baseFormat; SourceDataLine line; private boolean loop; private BufferedInputStream stream; // private ByteArrayInputStream stream; /** * recreate the stream * */ public void reset() < try < stream.reset(); in = AudioSystem.getAudioInputStream(stream); din = AudioSystem.getAudioInputStream(decodedFormat, in); line = getLine(decodedFormat); >catch (Exception e) < e.printStackTrace(); >> public void close() < try < line.close(); din.close(); in.close(); >catch (IOException e) < >> Sound(String filename, boolean loop) < this(filename); this.loop = loop; >Sound(String filename) < this.loop = false; try < InputStream raw = Object.class.getResourceAsStream(filename); stream = new BufferedInputStream(raw); // ByteArrayOutputStream out = new ByteArrayOutputStream(); // byte[] buffer = new byte[1024]; // int read = raw.read(buffer); // while( read >0 ) < // out.write(buffer, 0, read); // read = raw.read(buffer); // >// stream = new ByteArrayInputStream(out.toByteArray()); in = AudioSystem.getAudioInputStream(stream); din = null; if (in != null) < baseFormat = in.getFormat(); decodedFormat = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, baseFormat .getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat .getSampleRate(), false); din = AudioSystem.getAudioInputStream(decodedFormat, in); line = getLine(decodedFormat); >> catch (UnsupportedAudioFileException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >catch (LineUnavailableException e) < e.printStackTrace(); >> private SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException < SourceDataLine res = null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); res = (SourceDataLine) AudioSystem.getLine(info); res.open(audioFormat); return res; >public void play() < try < boolean firstTime = true; while (firstTime || loop) < firstTime = false; byte[] data = new byte[4096]; if (line != null) < line.start(); int nBytesRead = 0; while (nBytesRead != -1) < nBytesRead = din.read(data, 0, data.length); if (nBytesRead != -1) line.write(data, 0, nBytesRead); >line.drain(); line.stop(); line.close(); reset(); > > > catch (IOException e) < e.printStackTrace(); >> > 

Источник

How can I write a WAV file from byte array in java? [closed]

It’s difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.

I would like to write the Wav file from byte array and I also want to split channels from the input wav file The Java Sound API shows that you can record music from a TargetDataLine and as an example shows the data being written to a byte array. But writing this byte array out into its own file is fairly useless since it is not in the WAV file format and cannot be played in other applications. How do I write sound files using the javax.sound.sampled package?

2 Answers 2

I have used this in the past for going from Wav -> byte[] and byte[] -> Wav

 package GlobalUtilities; import java.applet.Applet; import java.applet.AudioClip; import java.net.URISyntaxException; import java.util.logging.Level; import java.util.logging.Logger; import java.io.*; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import javax.sound.sampled.*; /** * This class handles the reading, writing, and playing of wav files. It is * also capable of converting the file to its raw byte [] form. * * based on code by Evan Merz modified by Dan Vargo * @author dvargo */ public class Wav < /* WAV File Specification FROM http://ccrma.stanford.edu/courses/422/projects/WaveFormat/ The canonical WAVE format starts with the RIFF header: 0 4 ChunkID Contains the letters "RIFF" in ASCII form (0x52494646 big-endian form). 4 4 ChunkSize 36 + SubChunk2Size, or more precisely: 4 + (8 + SubChunk1Size) + (8 + SubChunk2Size) This is the size of the rest of the chunk following this number. This is the size of the entire file in bytes minus 8 bytes for the two fields not included in this count: ChunkID and ChunkSize. 8 4 Format Contains the letters "WAVE" (0x57415645 big-endian form). The "WAVE" format consists of two subchunks: "fmt " and "data": The "fmt " subchunk describes the sound data's format: 12 4 Subchunk1ID Contains the letters "fmt " (0x666d7420 big-endian form). 16 4 Subchunk1Size 16 for PCM. This is the size of the rest of the Subchunk which follows this number. 20 2 AudioFormat PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression. 22 2 NumChannels Mono = 1, Stereo = 2, etc. 24 4 SampleRate 8000, 44100, etc. 28 4 ByteRate == SampleRate * NumChannels * BitsPerSample/8 32 2 BlockAlign == NumChannels * BitsPerSample/8 The number of bytes for one sample including all channels. I wonder what happens when this number isn't an integer? 34 2 BitsPerSample 8 bits = 8, 16 bits = 16, etc. The "data" subchunk contains the size of the data and the actual sound: 36 4 Subchunk2ID Contains the letters "data" (0x64617461 big-endian form). 40 4 Subchunk2Size == NumSamples * NumChannels * BitsPerSample/8 This is the number of bytes in the data. You can also think of this as the size of the read of the subchunk following this number. 44 * Data The actual sound data. The thing that makes reading wav files tricky is that java has no unsigned types. This means that the binary data can't just be read and cast appropriately. Also, we have to use larger types than are normally necessary. In many languages including java, an integer is represented by 4 bytes. The issue here is that in most languages, integers can be signed or unsigned, and in wav files the integers are unsigned. So, to make sure that we can store the proper values, we have to use longs to hold integers, and integers to hold shorts. Then, we have to convert back when we want to save our wav data. It's complicated, but ultimately, it just results in a few extra functions at the bottom of this file. Once you understand the issue, there is no reason to pay any more attention to it. ALSO: This code won't read ALL wav files. This does not use to full specification. It just uses a trimmed down version that most wav files adhere to. */ ByteArrayOutputStream byteArrayOutputStream; AudioFormat audioFormat; TargetDataLine targetDataLine; AudioInputStream audioInputStream; SourceDataLine sourceDataLine; float frequency = 8000.0F; //8000,11025,16000,22050,44100 int samplesize = 16; private String myPath; private long myChunkSize; private long mySubChunk1Size; private int myFormat; private long myChannels; private long mySampleRate; private long myByteRate; private int myBlockAlign; private int myBitsPerSample; private long myDataSize; // I made this public so that you can toss whatever you want in here // maybe a recorded buffer, maybe just whatever you want public byte[] myData; public Wav() < myPath = ""; >// constructor takes a wav path public Wav(String tmpPath) < myPath = tmpPath; >// get/set for the Path property public String getPath() < return myPath; >public void setPath(String newPath) < myPath = newPath; >// read a wav file into this class public boolean read() < DataInputStream inFile = null; myData = null; byte[] tmpLong = new byte[4]; byte[] tmpInt = new byte[2]; try < inFile = new DataInputStream(new FileInputStream(myPath)); //System.out.println("Reading wav file. \n"); // for debugging only String chunkID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte(); inFile.read(tmpLong); // read the ChunkSize myChunkSize = byteArrayToLong(tmpLong); String format = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte(); // print what we've read so far //System.out.println("chunkID:" + chunkID + " chunk1Size:" + myChunkSize + " format:" + format); // for debugging only String subChunk1ID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte(); inFile.read(tmpLong); // read the SubChunk1Size mySubChunk1Size = byteArrayToLong(tmpLong); inFile.read(tmpInt); // read the audio format. This should be 1 for PCM myFormat = byteArrayToInt(tmpInt); inFile.read(tmpInt); // read the # of channels (1 or 2) myChannels = byteArrayToInt(tmpInt); inFile.read(tmpLong); // read the samplerate mySampleRate = byteArrayToLong(tmpLong); inFile.read(tmpLong); // read the byterate myByteRate = byteArrayToLong(tmpLong); inFile.read(tmpInt); // read the blockalign myBlockAlign = byteArrayToInt(tmpInt); inFile.read(tmpInt); // read the bitspersample myBitsPerSample = byteArrayToInt(tmpInt); // print what we've read so far //System.out.println("SubChunk1ID:" + subChunk1ID + " SubChunk1Size:" + mySubChunk1Size + " AudioFormat:" + myFormat + " Channels:" + myChannels + " SampleRate:" + mySampleRate); // read the data chunk header - reading this IS necessary, because not all wav files will have the data chunk here - for now, we're just assuming that the data chunk is here String dataChunkID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte(); inFile.read(tmpLong); // read the size of the data myDataSize = byteArrayToLong(tmpLong); // read the data chunk myData = new byte[(int) myDataSize]; inFile.read(myData); // close the input stream inFile.close(); >catch (Exception e) < return false; >return true; // this should probably be something more descriptive > // write out the wav file public boolean save() < try < DataOutputStream outFile = new DataOutputStream(new FileOutputStream(myPath + "temp")); // write the wav file per the wav file format outFile.writeBytes("RIFF"); // 00 - RIFF outFile.write(intToByteArray((int) myChunkSize), 0, 4); // 04 - how big is the rest of this file? outFile.writeBytes("WAVE"); // 08 - WAVE outFile.writeBytes("fmt "); // 12 - fmt outFile.write(intToByteArray((int) mySubChunk1Size), 0, 4); // 16 - size of this chunk outFile.write(shortToByteArray((short) myFormat), 0, 2); // 20 - what is the audio format? 1 for PCM = Pulse Code Modulation outFile.write(shortToByteArray((short) myChannels), 0, 2); // 22 - mono or stereo? 1 or 2? (or 5 or . ) outFile.write(intToByteArray((int) mySampleRate), 0, 4); // 24 - samples per second (numbers per second) outFile.write(intToByteArray((int) myByteRate), 0, 4); // 28 - bytes per second outFile.write(shortToByteArray((short) myBlockAlign), 0, 2); // 32 - # of bytes in one sample, for all channels outFile.write(shortToByteArray((short) myBitsPerSample), 0, 2); // 34 - how many bits in a sample(number)? usually 16 or 24 outFile.writeBytes("data"); // 36 - data outFile.write(intToByteArray((int) myDataSize), 0, 4); // 40 - how big is this data chunk outFile.write(myData); // 44 - the actual data itself - just a long string of numbers >catch (Exception e) < System.out.println(e.getMessage()); return false; >return true; > // return a printable summary of the wav file public String getSummary() < //String newline = System.getProperty("line.separator"); String newline ; String summary = "Format: " + myFormat + newline + "Channels: " + myChannels + newline + "SampleRate: " + mySampleRate + newline + "ByteRate: " + myByteRate + newline + "BlockAlign: " + myBlockAlign + newline + "BitsPerSample: " + myBitsPerSample + newline + "DataSize: " + myDataSize + ""; return summary; >public byte[] getBytes() < read(); return myData; >/** * Plays back audio stored in the byte array using an audio format given by * freq, sample rate, ect. * @param data The byte array to play */ public void playAudio(byte[] data) < try < byte audioData[] = data; //Get an input stream on the byte array containing the data InputStream byteArrayInputStream = new ByteArrayInputStream(audioData); AudioFormat audioFormat = getAudioFormat(); audioInputStream = new AudioInputStream(byteArrayInputStream, audioFormat, audioData.length / audioFormat.getFrameSize()); DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat); sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo); sourceDataLine.open(audioFormat); sourceDataLine.start(); //Create a thread to play back the data and start it running. It will run \ //until all the data has been played back. Thread playThread = new Thread(new PlayThread()); playThread.start(); >catch (Exception e) < System.out.println(e); >> /** * This method creates and returns an AudioFormat object for a given set * of format parameters. If these parameters don't work well for * you, try some of the other allowable parameter values, which * are shown in comments following the declarations. * @return */ private AudioFormat getAudioFormat() < float sampleRate = frequency; //8000,11025,16000,22050,44100 int sampleSizeInBits = samplesize; //8,16 int channels = 1; //1,2 boolean signed = true; //true,false boolean bigEndian = false; //true,false //return new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, 8000.0f, 8, 1, 1, //8000.0f, false ); return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian); >public void playWav(String filePath) < try < AudioClip clip = (AudioClip) Applet.newAudioClip(new File(filePath).toURI().toURL()); clip.play(); >catch (Exception e) < Logger.getLogger(Wav.class.getName()).log(Level.SEVERE, null, e); >> // =========================== // CONVERT BYTES TO JAVA TYPES // =========================== // these two routines convert a byte array to a unsigned short public static int byteArrayToInt(byte[] b) < int start = 0; int low = b[start] & 0xff; int high = b[start + 1] & 0xff; return (int) (high >8) & 0x000000FF); b[2] = (byte) ((i >> 16) & 0x000000FF); b[3] = (byte) ((i >> 24) & 0x000000FF); return b; > // convert a short to a byte array public static byte[] shortToByteArray(short data) < return new byte[]>> 8) & 0xff)>; > /** * Inner class to play back the data that was saved */ class PlayThread extends Thread < byte tempBuffer[] = new byte[10000]; public void run() < try < int cnt; //Keep looping until the input // read method returns -1 for // empty stream. while ((cnt = audioInputStream.read(tempBuffer, 0, tempBuffer.length)) != -1) < if (cnt >0) < //Write data to the internal // buffer of the data line // where it will be delivered // to the speaker. sourceDataLine.write(tempBuffer, 0, cnt); >> //Block and wait for internal // buffer of the data line to // empty. sourceDataLine.drain(); sourceDataLine.close(); > catch (Exception e) < System.out.println(e); System.exit(0); >> > > 

Источник

How to play an mp3 file in java

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.

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.

3 Answers 3

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) > > 
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.

To be sure that you are using a supported format file, check here:

If you are using windows7, you may have to read this as well:

Источник

Оцените статью