如何让用户选择音频文件并在 Java 中播放

Posted

技术标签:

【中文标题】如何让用户选择音频文件并在 Java 中播放【英文标题】:How to have the user choose an audio file and play it in Java 【发布时间】:2011-04-19 23:49:18 【问题描述】:

我希望能够制作一个 GUI 或控制台应用程序,用户单击一个按钮从他们的计算机中选择一个音频文件(兼容格式)并播放它,因为我对 GUI 完全没有经验,如果能提示我如何实现暂停和播放按钮,以及音量滑动/拨号和停止按钮,那就太好了。我只知道我必须导入java.io.*sun.audio.*

编辑 我当前的代码是这样的:

import sun.audio.*; //import the sun.audio package
import java.awt.*;
import java.io.*;


public class Boombox extends Frame implements FilenameFilter 

/**
 * 
 */
private static final long serialVersionUID = 4914433234899026080L;
Button openButton = new Button("Open");  
Button playButton = new Button("Play");
Button loopButton = new Button("Loop");
Button stopButton = new Button("Stop");
Label filename = new Label("                   ");
File theFile = null;
@SuppressWarnings( "restriction" )
AudioData theData = null;
InputStream nowPlaying = null;

@SuppressWarnings( "deprecation" )
public Boombox() 
    super("Boombox");
    resize(300, 200);
    Panel north = new Panel();
    north.setLayout(new FlowLayout(FlowLayout.LEFT));
    north.add(new Label("File: "));
    north.add("North", filename);
    add("North", north);
    Panel south = new Panel();
    south.add(openButton);
    south.add(playButton);
    south.add(loopButton);
    south.add(stopButton);
    add("South", south);


@SuppressWarnings("deprecation")
public static void main(String[] args) 
    Boombox sp = new Boombox();
    sp.show();


@SuppressWarnings( "deprecation", "restriction" )
public void open() 
    FileDialog fd = new FileDialog(this, "Please select a .au file:");
    fd.setFilenameFilter(this);
    fd.show();
    try 
        theFile = new File(fd.getDirectory() + "/" + fd.getFile());
        if (theFile != null) 
            filename.setText(theFile.getName());
            FileInputStream fis = new FileInputStream(theFile);
            Audiostream as = new AudioStream(fis);
            theData = as.getData();
        
    
    catch (IOException e) 
        System.err.println(e);
    


@SuppressWarnings("restriction")
public void play() 
    stop();    
    if (theData == null) open();
    if (theData != null) 
        AudioDataStream ads = new AudioDataStream(theData);
        AudioPlayer.player.start(ads);
        nowPlaying = ads;
    


@SuppressWarnings("restriction")
public void stop() 
    if (nowPlaying != null) 
        AudioPlayer.player.stop(nowPlaying);
        nowPlaying = null;
    


@SuppressWarnings("restriction")
public void loop() 
    stop();
    if (theData == null) open();
    if (theData != null) 
        ContinuousAudioDataStream cads = new ContinuousAudioDataStream(theData);
        AudioPlayer.player.start(cads);
        nowPlaying = cads;
    


public boolean action(Event e, Object what) 

    if (e.target == playButton) 
        play();
        return true;
    
    else if (e.target == openButton) 
        open();
        return true;
    
    else if (e.target == loopButton) 
        loop();
        return true;
    
    else if (e.target == stopButton) 
        stop();
        return true;
    

    return false;



public boolean accept(File dir, String name) 

    name = name.toLowerCase();
    if (name.endsWith(".au")) return true;
    if (name.endsWith(".wav")) return true;
    return false;




【问题讨论】:

1) “你所知道的”是错误的。 2) 将鞋拔按钮和滑块插入(纯)控制台应用程序是很棘手的。 我在想,如果它是一个控制台应用程序,会有改变音量、停止和暂停的命令,但我想我已经决定这行不通,而是我我要做一个图形用户界面 【参考方案1】:

这是播放短片的简单方法。

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

class ClipTest 

  public static void main(String[] args) throws Exception 
    String clipName = null;
    if (args.length==1) 
      clipName = args[0];
     else 
      clipName = "http://pscode.org/media/leftright.wav";
    
    System.out.println("Looping '" + clipName + "'.");
    URL url = new URL(clipName);
    AudioInputStream ais = AudioSystem.getAudioInputStream(url);
    Clip clip = AudioSystem.getClip();
    clip.open( ais );
    clip.loop(2);
    clip.start();
    JOptionPane.showMessageDialog(null, "Close to end..");
  

示例输入/输出。

F:\proj>java ClipTest http://pscode.org/media/100_2817-linear.wav
Looping 'http://pscode.org/media/100_2817-linear.wav'.

F:\proj>java ClipTest
Looping 'http://pscode.org/media/leftright.wav'.

F:\proj>

【讨论】:

是的,但我希望能够接受用户选择的音频文件 查看编辑。向 CLI 应用程序添加了上述功能。请注意,您应该将 GUI 与“播放声音”分开(并针对每个问题提出单独的问题)。它们在很大程度上是不同的东西。【参考方案2】:

这个java使用sun类:

import sun.audio.*; //import the sun.audio package
import java.awt.*;
import java.io.*;


public class SoundPlayer extends Frame implements FilenameFilter 

  Button openButton = new Button("Open");  
  Button playButton = new Button("Play");
  Button loopButton = new Button("Loop");
  Button stopButton = new Button("Stop");
  Label filename = new Label("                   ");
  File theFile = null;
  AudioData theData = null;
  InputStream nowPlaying = null;

  public SoundPlayer() 
    super("Sound Player");
    resize(300, 200);
    Panel north = new Panel();
    north.setLayout(new FlowLayout(FlowLayout.LEFT));
    north.add(new Label("File: "));
    north.add("North", filename);
    add("North", north);
    Panel south = new Panel();
    south.add(openButton);
    south.add(playButton);
    south.add(loopButton);
    south.add(stopButton);
    add("South", south);
  

  public static void main(String[] args) 
    SoundPlayer sp = new SoundPlayer();
    sp.show();
  

  public void open() 
    FileDialog fd = new FileDialog(this, "Please select a .au file:");
    fd.setFilenameFilter(this);
    fd.show();
    try 
      theFile = new File(fd.getDirectory() + "/" + fd.getFile());
      if (theFile != null) 
        filename.setText(theFile.getName());
        FileInputStream fis = new FileInputStream(theFile);
        AudioStream as = new AudioStream(fis);
        theData = as.getData();
      
    
    catch (IOException e) 
      System.err.println(e);
    
  

  public void play() 
    stop();    
    if (theData == null) open();
    if (theData != null) 
      AudioDataStream ads = new AudioDataStream(theData);
      AudioPlayer.player.start(ads);
      nowPlaying = ads;
    
  

  public void stop() 
    if (nowPlaying != null) 
      AudioPlayer.player.stop(nowPlaying);
      nowPlaying = null;
    
  

  public void loop() 
    stop();
    if (theData == null) open();
    if (theData != null) 
      ContinuousAudioDataStream cads = new ContinuousAudioDataStream(theData);
      AudioPlayer.player.start(cads);
      nowPlaying = cads;
    
  

  public boolean action(Event e, Object what) 

    if (e.target == playButton) 
      play();
      return true;
    
    else if (e.target == openButton) 
      open();
      return true;
    
    else if (e.target == loopButton) 
      loop();
      return true;
    
    else if (e.target == stopButton) 
      stop();
      return true;
    

    return false;

  

  public boolean accept(File dir, String name) 

    name = name.toLowerCase();
    if (name.endsWith(".au")) return true;
    if (name.endsWith(".wav")) return true;
    return false;

  


【讨论】:

某些代码(例如 AudioData)被标记为错误,因为它们“由于所需库的限制而无法访问”。 好的,现在我已经解决了这个问题,它说:java.lang.NoClassDefFoundError: SoundPlayer Caused by: java.lang.ClassNotFoundException: SoundPlayer at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) Exception in thread "main"

以上是关于如何让用户选择音频文件并在 Java 中播放的主要内容,如果未能解决你的问题,请参考以下文章

如何在同一页面中播放多个音频文件?

如何将两个音频文件合并为一个并在javascript中合并后播放

存储音频路径并在网页上播放

如何反转 AAC 音频文件?

如何让我的两个音频播放器同时播放两首不同的歌曲?

如何在java中重复音频文件