views:

69

answers:

2

LAST EDIT - TWO SIMPLE ANSWERS NEEDED.

1) I was able to get the code working with a URL (it's the code from one of the responses below). But my song is in a wav file. When I try to do File url = new File("---");, it doesn't work.

Instead, in the stack trace (thanks for that tip!), it says

"Failed to allocate clip data: Requested buffer too large"

The song I'm trying to play is techno, about 3 minutes long.

How do I work around the clip data size issue?

A: 

You can do it using standard API

But if you are particularly interested in sound and manipulation of the same you should go for.

Java Media Framework

here is sample code

import javax.media.*;
import java.io.*;
import java.net.URL;

class mp3 extends Thread
{

private URL url;
private MediaLocator mediaLocator;
private Player playMP3;

public mp3(String mp3)
{
try{
   this.url = new URL(mp3);
   }catch(java.net.MalformedURLException e)
      {System.out.println(e.getMessage());}
}

public void run()
{

try{
   mediaLocator = new MediaLocator(url);     
   playMP3 = Manager.createPlayer(mediaLocator);
    }catch(java.io.IOException e)
      {System.out.println(e.getMessage());
    }catch(javax.media.NoPlayerException e)
      {System.out.println(e.getMessage());}

playMP3.addControllerListener(new ControllerListener()
  {
  public void controllerUpdate(ControllerEvent e)
     {
     if (e instanceof EndOfMediaEvent)
         {
         playMP3.stop();
         playMP3.close();
         }
     }
  }
 );
 playMP3.realize();
 playMP3.start();
 } 
}

public class playmp3{
  public static void main(String[] args)
  {
  mp3 t = new mp3("file:///C://JavaApplications//cd.mp3");
  t.start();
  }
}
org.life.java
Not really. Functionality for playing sound is part of the standard API, so there is no need to add an additional huge, overly complex and more or less abandoned extension like JMF.
jarnbjo
@jarnbjo : Yeah, actually It got skipped out , updated the answer.
org.life.java
+1  A: 

Look at the classes of the Java Sound API for sampled sound. Particularly the Clip interface and the AudioSystem class.

Java Sound uses the SPI to add support for extra formats to the defaults built in to the J2SE. You can add the JMF based mp3plugin.jar to provide support for MP3s to JavaSound.


For playing WAVs in a loop, see this small example..

import java.net.URL;
import javax.sound.sampled.*;

public class LoopSound {

  public static void main(String[] args) throws Exception {
    URL url = new URL(
      "http://pscode.org/media/leftright.wav");
    Clip clip = AudioSystem.getClip();
    AudioInputStream ais = AudioSystem.
      getAudioInputStream( url );
    clip.open(ais);
    clip.loop(5);
    javax.swing.JOptionPane.showMessageDialog(null, "Close to exit!");
  }
} 
Andrew Thompson
This worked for your sound, but when I used my file it said "Clip did not allocate memory needed..."
Marky Mark