Java inbuilt libraries support only AIFC, AIFF, AU, SND and WAVE formats. Here I only discussed playing an audio file using Clip only and see the various methods of a clip.
PlayAudio.java
.Audio.java
.PlayAudio.java
import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class PlayAudio {
public static void main(String[] args) throws
UnsupportedAudioFileException, IOException,
LineUnavailableException {
PlayMp3 playMp3;
playMp3=new PlayMp3();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter Choice :-");
System.out.println("1. Play");
System.out.println("2. pause");
System.out.println("3. resume");
System.out.println("4. restart");
System.out.println("5. stop");
System.out.println(PlayMp3.status);
System.out.println(":::- ");
int c = sc.nextInt();
if (c ==5){
playMp3.stop();
break;
}
switch (c) {
case 1:
playMp3.play();
break;
case 2:
playMp3.pause();
break;
case 3:
playMp3.resume();
break;
case 4:
playMp3.restart();
break;
case 5:
playMp3.stop();
default:
System.out.println("Please Enter Valid Option :-");
}
}
sc.close();
}
}
Audio.java
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class Audio {
private String filePath="mp.snd";
public static String status="paused";
private Long currentFrame=0L;
private Clip clip;
private AudioInputStream audioInputStream;
public Audio() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
audioInputStream = AudioSystem.getAudioInputStream(new File(filePath));
clip = AudioSystem.getClip();
clip.open(audioInputStream);
}
public void play(){
clip.start();
status = "playing";
}
public void pause(){
if (status.equals("paused")) {
System.out.println("audio is already paused");
return;
}
currentFrame = clip.getMicrosecondPosition();
clip.stop();
status = "paused";
}
public void resume() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
if (status.equals("play"))
{
System.out.println("Audio is already being playing");
return;
}
clip.close();
//starts again and goes to currentFrame
resetAudioStream();
clip.setMicrosecondPosition(currentFrame);
play();
status="playing";
}
public void restart() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
clip.stop();
clip.close();
resetAudioStream();
currentFrame = 0L;
clip.setMicrosecondPosition(0);
play();
status="Playing from start";
}
public void stop(){
currentFrame = 0L;
clip.stop();
clip.close();
status="stopped";
}
private void resetAudioStream() throws IOException, UnsupportedAudioFileException, LineUnavailableException {
audioInputStream = AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
clip.open(audioInputStream);
}
}