使用Clip对象播放多个声音片段

使用Clip对象播放多个声音片段,第1张

使用Clip对象播放多个声音片段

有一对夫妇,你也许能够实现这一目标的方式,但其基本思想是,你想注册

LineListener
一个
Clip
和监控的
LineEvent.Type.STOP
事件,并重新启用按钮

例如。这将查找

.wav
给定目录中的所有文件,并为每个文件创建一个按钮。单击后,按钮(或更重要的是,底层按钮
Action
)将被禁用并播放音频。设置为时
STOP
,将
Action
重新启用(和按钮的扩展名)。

声音API可以同时播放多种声音

import java.awt.EventQueue;import java.awt.GridBagConstraints;import java.awt.GridBagLayout;import java.awt.event.ActionEvent;import java.beans.PropertyChangeEvent;import java.beans.PropertyChangeListener;import java.io.File;import java.io.FileFilter;import java.io.IOException;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URL;import java.util.concurrent.ExecutionException;import java.util.logging.Level;import java.util.logging.Logger;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.Clip;import javax.sound.sampled.LineEvent;import javax.sound.sampled.LineListener;import javax.sound.sampled.LineUnavailableException;import javax.sound.sampled.UnsupportedAudioFileException;import javax.swing.AbstractAction;import javax.swing.JButton;import javax.swing.Jframe;import javax.swing.JPanel;import javax.swing.SwingWorker;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;public class Test {    public static void main(String[] args) {        new Test();    }    public Test() {        EventQueue.invokeLater(new Runnable() { @Override public void run() {     try {         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());     } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {         ex.printStackTrace();     }     Jframe frame = new Jframe("Testing");     frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);     frame.add(new TestPane());     frame.pack();     frame.setLocationRelativeTo(null);     frame.setVisible(true); }        });    }    public class TestPane extends JPanel {        public TestPane() { File[] musicFiles = new File("a directory somewhere").listFiles(new FileFilter() {     @Override     public boolean accept(File pathname) {         return pathname.getName().toLowerCase().endsWith(".wav");     } }); setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.fill = GridBagConstraints.HORIZONTAL; for (File music : musicFiles) {     try {         JButton btn = new JButton(new AudioAction(music.getName(), music.toURI().toURL()));         add(btn, gbc);     } catch (MalformedURLException ex) {         ex.printStackTrace();     } }        }    }    public class AudioAction extends AbstractAction {        private URL audio;        public AudioAction(String name, URL audioSource) { super(name); this.audio = audioSource;        }        public URL getAudioSource() { return audio;        }        @Override        public void actionPerformed(ActionEvent e) { setEnabled(false); try (InputStream is = getAudioSource().openStream()) {     AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(is);     Clip play = AudioSystem.getClip();     play.addLineListener(new LineListener() {         @Override         public void update(LineEvent event) {  System.out.println(event.getframePosition());  if (event.getType().equals(LineEvent.Type.STOP)) {      setEnabled(true);  }         }     });     play.open(audioInputStream);     play.start(); } catch (IOException | LineUnavailableException | UnsupportedAudioFileException exp) {     exp.printStackTrace(); }        }    }}

nb:我尝试使用

Clip#drain
(在后台线程中),但是它仅适用于第一个剪辑,随后的剪辑基本上跳过了该方法,因此我选择了
LineListener

现在有了更好的资源管理
import java.awt.EventQueue;import java.awt.GridBagConstraints;import java.awt.GridBagLayout;import java.awt.event.ActionEvent;import java.io.File;import java.io.FileFilter;import java.io.IOException;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URL;import java.util.logging.Level;import java.util.logging.Logger;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.Clip;import javax.sound.sampled.LineEvent;import javax.sound.sampled.LineListener;import javax.sound.sampled.LineUnavailableException;import javax.sound.sampled.UnsupportedAudioFileException;import javax.swing.AbstractAction;import javax.swing.JButton;import javax.swing.Jframe;import javax.swing.JPanel;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;public class Test {    public static void main(String[] args) {        new Test();    }    public Test() {        EventQueue.invokeLater(new Runnable() { @Override public void run() {     try {         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());     } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {         ex.printStackTrace();     }     Jframe frame = new Jframe("Testing");     frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);     frame.add(new TestPane());     frame.pack();     frame.setLocationRelativeTo(null);     frame.setVisible(true); }        });    }    public class TestPane extends JPanel {        public TestPane() { File[] musicFiles = new File("...").listFiles(new FileFilter() {     @Override     public boolean accept(File pathname) {         return pathname.getName().toLowerCase().endsWith(".wav");     } }); setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.fill = GridBagConstraints.HORIZONTAL; for (File music : musicFiles) {     try {         JButton btn = new JButton(new AudioAction(music.getName(), music.toURI().toURL()));         add(btn, gbc);     } catch (MalformedURLException exp) {         exp.printStackTrace();     } }        }    }    public class AudioAction extends AbstractAction {        private AudioPlayer player;        public AudioAction(String name, URL audioSource) { super(name); player = new AudioPlayer(audioSource);        }        @Override        public void actionPerformed(ActionEvent e) { if (player.isPlaying()) {     player.stop(); } else {     try {         player.play();     } catch (IOException | LineUnavailableException | UnsupportedAudioFileException ex) {         ex.printStackTrace();     } }        }    }    public class AudioPlayer {        private Clip clip;        private URL url;        public AudioPlayer(URL url) { this.url = url;        }        public boolean isPlaying() { return clip != null && clip.isRunning();        }        protected void open() throws IOException, LineUnavailableException, UnsupportedAudioFileException { clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(url.openStream()));        }        public void play() throws IOException, LineUnavailableException, UnsupportedAudioFileException { if (clip == null || !clip.isRunning()) {     open();     clip.setframePosition(0);     clip.start(); }        }        public void stop() { if (clip != null && clip.isRunning()) {     clip.stop();     clip.flush();     dispose(); }        }        public void dispose() { try {     clip.close(); } finally {     clip = null; }        }    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5478408.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存