Friday, March 18, 2016

Playing Audio File (WAV)

This simple audio player utilizes JMF. Sound files (.wav) are first loaded from a predetermined folder. File names are then added to a list. The ListSelectionListener interface allows the user to select one of the sound files to be played.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.media.Manager;
import javax.media.Player;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class AudioPlayer extends JFrame{
    private Player audioPlayer=null;
    private JList lfiles=null;
    private File dir=null;
    
    public AudioPlayer(){
        setSize(300,200);
        
        lfiles=new JList();
        dir=new File("C://Users/MARIO/Documents/sound");
        String files[]=dir.list();
        lfiles.setListData(files);
        lfiles.addListSelectionListener(new ListHandler());
            
        setLayout(new BorderLayout());
        add("Center",lfiles);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    
    class ListHandler implements ListSelectionListener{
        public void valueChanged(ListSelectionEvent ev) {
            String filename=dir+"\\"+(String)lfiles.getSelectedValue();
            System.out.println(filename);
            File f=new File(filename);
            try{
                audioPlayer=Manager.createRealizedPlayer(f.toURL());
                audioPlayer.start();
            }catch(Exception e){
                                
            }
        }
    }
    
    public static void main(String[] args){
        new AudioPlayer();
    }
}

No comments:

Post a Comment