import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.sound.sampled.*;
public class AudioTest extends JFrame implements ActionListener
{
AudioFormat audioFormat;
AudioInputStream audioInputStream;
SourceDataLine sourceDataLine;
boolean stopPlayback = false;
private final JButton stopBtn = new JButton("Stop");
private final JButton playBtn = new JButton("Play");
private final JTextField textField = new JTextField("junk.au");
public static void main(String[] args)
{
AudioTest gui = new AudioTest();
gui.setVisible(true);
}
public AudioTest()
{
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
playBtn.addActionListener(this);
stopBtn.addActionListener(this);
getContentPane().add(playBtn, "West");
getContentPane().add(stopBtn, "East");
getContentPane().add(textField, "North");
setTitle("Audio Test");
addWindowListener(new WindowDestroyer());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(250, 70);
}
private void playAudio()
{
try
{
File soundFile = new File(textField.getText());
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
audioFormat = audioInputStream.getFormat();
System.out.println(audioFormat);
DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine)AudioSystem.getLine(dataLineInfo);
new PlayThread().start();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
private class PlayThread extends Thread
{
byte tempBuffer[] = new byte[10000];
public void run()
{
try
{
sourceDataLine.open(audioFormat);
sourceDataLine.start();
int cnt;
while((cnt = audioInputStream.read(
tempBuffer, 0, tempBuffer.length)) != 1
&& stopPlayback == false)
{
if(cnt >0)
{
sourceDataLine.write(tempBuffer, 0, cnt);
}
}
sourceDataLine.drain();
sourceDataLine.close();
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
stopPlayback = false;
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Play"))
{
stopBtn.setEnabled(true);
playBtn.setEnabled(false);
playAudio();
}
else if(e.getActionCommand().equals("Stop"))
{
stopPlayback = true;
}
}
}
我一直在试图弄清楚为什么音频输入流有问题。文件名是正确的,它将它带入文件,但具有getAudioInputStream的行有问题。这是我计划工作的项目的测试代码,我熟悉所有内容,但我一直在收到错误。
答案 0 :(得分:1)
您需要提供完整的路径和文件名,例如......
工作只是找...
您可能需要考虑尝试使用其他音频格式(例如.wav)