} } 使用上面的如下: /** *TestWav.java * Created on 4:22:18 PM Feb 20, 2009 *@author Quasar063501 *@version 0.1 * */ public class TestWav { public static void main(String args[]) { AePlayWave p = new AePlayWave("src/bg.wav"); p.start(); } }
import javax.sound.midi.*;class Test { public static void main(String[] args) { try { Sequencer sequencer = MidiSystem.getSequencer(); sequencer.open(); Sequence seq = new Sequence(Sequence.PPQ, 4); Track track = seq.createTrack(); for (int i = 5; i < 61; i++) { track.add(makeEvent(144, 1, i, 100, i)); track.add(makeEvent(128, 1, i, 100, i + 2)); } // end loop sequencer.setSequence(seq); sequencer.setTempoInBPM(220); sequencer.start(); quitProgram(sequencer); } catch (Exception ex) { ex.printStackTrace(); } } // end main public static void quitProgram(Sequencer sequencer) { while (sequencer.isRunning()) { System.out.println("isRunning"); } System.exit(0); } public static MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) { MidiEvent event = null; try { ShortMessage a = new ShortMessage(); a.setMessage(comd, chan, one, two); event = new MidiEvent(a, tick); } catch (Exception e) { e.printStackTrace(); } return event; }}
AU,AIFF,WAV,MIDI,RFM等格式的音频.
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.GainControl;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PrefetchCompleteEvent;
import javax.media.RealizeCompleteEvent;
import javax.media.StopEvent;
import javax.media.Time;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;public class SoundServer {
private static final int SOCKET_BACKLOG = 1;
private static final int PORT = 7890;
private static final String BIND_ADDRESS = "127.0.0.1";
private static final String PLAY_COMMAND = "play";
private static final String STOP_COMMAND = "stop";
private static final String DELIMITER = "\\|";
private static final float DEFAULT_VOLUME = 0.4f; private static final Logger log = Logger.getAnonymousLogger(); private final Map<String, SoundPlayer> playerMap; private SoundServer() {
playerMap = new ConcurrentHashMap<String, SoundPlayer>();
} private String playSound(String file, float volume) {
SoundPlayer player = new SoundPlayer(file, volume);
playerMap.put(file, player);
player.playSound();
return "Playing:------------" + file;
} private String stopSound(String file) {
SoundPlayer player = playerMap.get(file);
player.stopSound();
return "Stopped:------------" + file;
} private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream socketOut = socket.getOutputStream();
return new PrintWriter(socketOut, true);
} private BufferedReader getReader(Socket socket) throws IOException {
InputStream socketIn = socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
} private void start() throws IOException {
log.info("Sound Server started and bound to port " + PORT);
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT, SOCKET_BACKLOG, InetAddress.getByName(BIND_ADDRESS)); while (true) {
Socket socket = null;
BufferedReader br = null;
PrintWriter pw = null;
try {
socket = serverSocket.accept();
log.info("New connection accepted" +
socket.getInetAddress() + ":" + socket.getPort());
br = getReader(socket);
pw = getWriter(socket); String msg;
while ((msg = br.readLine()) != null) {
log.info("Received message: " + msg);
pw.println(executeInputCommand(msg));
if (msg.equals("bye"))
log.info("Stopping sound server");
break;
}
} catch (Throwable e) {
log.severe(e.toString() + " caught. Continuing sound server.");
}
finally {
try {
if (br != null) {
br.close();
}
} catch (Exception e) { /* swallow */ }
try {
if (pw != null) {
pw.close();
}
} catch (Exception e) { /* swallow */ }
try {
if (socket != null) {
socket.close();
}
} catch (Exception e) { /* swallow */ }
}
}
} finally {
serverSocket.close();
}
} private String executeInputCommand(String message) {
log.info("Attempting to execute command received " + message);
String[] commandArray = parseCommandArray(message);
if (commandArray.length < 2) {
log.warning("Received no command or no sound file to play or stop. Ignoring message with contents " + message);
return "";
} String command = commandArray[0];
String file = commandArray[1];
float volume = DEFAULT_VOLUME; if (commandArray.length > 2) {
try {
float f = Float.parseFloat(commandArray[2]);
volume = f / 100;
log.info("Setting volume to " + volume);
} catch (NumberFormatException nfe) {
// swallow - ignore and use default
}
} if (command.equals(PLAY_COMMAND)) {
return playSound(file, volume);
} else if (command.equals(STOP_COMMAND)) {
return stopSound(file);
} log.warning("Unknown command received " + command + " ignoring message " + message);
return "";
} private String[] parseCommandArray(String message) {
return message.split(DELIMITER);
} public static void main(String[] args) throws Exception {
try {
SoundServer server = new SoundServer();
server.start();
} catch (Exception e) {
e.printStackTrace();
}
} class SoundPlayer implements ControllerListener {
private Player player;
private String musicFile;
private float volume; SoundPlayer(String musicFile, float volume) {
this.musicFile = musicFile;
this.volume = volume;
} synchronized void playSound() {
log.info(musicFile + " being played");
try {
player = Manager.createPlayer(new MediaLocator("file:" + musicFile));
player.addControllerListener(this);
player.prefetch();
} catch (Exception ex) {
log.severe("Error caught trying to play sound " + musicFile + " " + ex.toString());
}
} synchronized void stopSound() {
log.info("Received request to stop sound: " + musicFile);
player.stop();
} public void controllerUpdate(ControllerEvent e) {
if (e instanceof EndOfMediaEvent) {
player.setMediaTime(new Time(0));
player.stop();
log.info(musicFile + " sound stopped");
} else if (e instanceof PrefetchCompleteEvent) {
log.info("Got prefetch complete event");
player.start();
} else if (e instanceof RealizeCompleteEvent) {
setVolume();
} else if (e instanceof StopEvent) {
player.close();
SoundServer.this.playerMap.remove(musicFile);
log.info("Player for " + musicFile + " cleaned up");
}
} public void setVolume() {
log.info("Setting volume for " + musicFile + " to " + this.volume);
GainControl gc = player.getGainControl();
gc.setLevel(this.volume);
}
}
}看不明白问哇 100分 呵呵呵
/**
*AePlayWave.java
* Created on 4:14:40 PM Feb 20, 2009
*@author Quasar063501
*@version 0.1
*
*/
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AePlayWave extends Thread {
private String filename;
private Position curPosition;
private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
enum Position {
LEFT, RIGHT, NORMAL
};
public AePlayWave(String wavfile) {
filename = wavfile;
curPosition = Position.NORMAL;
}
public AePlayWave(String wavfile, Position p) {
filename = wavfile;
curPosition = p;
}
public void run() {
File soundFile = new File(filename);
if (!soundFile.exists()) {
System.err.println("Wave file not found: " + filename);
return;
}
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
if (auline.isControlSupported(FloatControl.Type.PAN)) {
FloatControl pan = (FloatControl) auline
.getControl(FloatControl.Type.PAN);
if (curPosition == Position.RIGHT)
pan.setValue(1.0f);
else if (curPosition == Position.LEFT)
pan.setValue(-1.0f);
}
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}
使用上面的如下:
/**
*TestWav.java
* Created on 4:22:18 PM Feb 20, 2009
*@author Quasar063501
*@version 0.1
*
*/
public class TestWav {
public static void main(String args[]) {
AePlayWave p = new AePlayWave("src/bg.wav");
p.start();
}
}
public static void main(String[] args) {
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open(); Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack(); for (int i = 5; i < 61; i++) {
track.add(makeEvent(144, 1, i, 100, i));
track.add(makeEvent(128, 1, i, 100, i + 2));
} // end loop sequencer.setSequence(seq);
sequencer.setTempoInBPM(220);
sequencer.start(); quitProgram(sequencer); }
catch (Exception ex) {
ex.printStackTrace();
}
} // end main public static void quitProgram(Sequencer sequencer) {
while (sequencer.isRunning()) {
System.out.println("isRunning");
} System.exit(0);
} public static MidiEvent makeEvent(int comd, int chan, int one, int two,
int tick) {
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
}
catch (Exception e) {
e.printStackTrace();
}
return event;
}}
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.GainControl;
import javax.media.Manager;无法导入包;都是错误
6楼的也是,全是错误,不能解析
import javax.media.*; 还是无法导入,其他包都正常,在JDK API中,也找不到javax.media.*
http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/download.html 下载JMF
AU,AIFF,WAV,MIDI,RFM等格式的音频.
//新建一个img文件夹,里面放上要播放的音乐。mid类型的吧。
import java.applet.*;
import java.awt.event.*;
import java.awt.*;public class PlayAudio extends Applet
implements ActionListener{
AudioClip audio;
Button btExit,btOpen,btPlay,btLoop,btStop;
/**
*<br>方法说明:初始化Applet
*<br>输入参数:
*<br>返回类型:
*/
public void init() {
//加载声音文件
audio = getAudioClip(getDocumentBase(),"img/1.mid");//这里放上你加在新建文件夹里面的歌曲名称
//构造按钮
setLayout(new FlowLayout());
btPlay=new Button("Play");
btPlay.addActionListener(this);
btLoop=new Button("Loop");
btLoop.addActionListener(this);
btStop=new Button("Stop");
btStop.addActionListener(this); //给Play按钮添加一个监听事件
//将按钮添加到Applet中
add(btPlay);
add(btLoop);
add(btStop);}public void actionPerformed(ActionEvent e) { //如果点击的是Play按钮
if (e.getSource()==btPlay) {
play();
}
//如果点击的是loop按钮
if (e.getSource()==btLoop) {
loop();
}
//如果点击的是stop按钮
if (e.getSource()==btStop) {
stop();
}
}
/**
*<br>方法说明:播放声音
*<br>输入参数:
*<br>返回类型:
*/
public void play(){
if (audio!=null) stop();
audio.play();
}
/**
*<br>方法说明:循环播放声音
*<br>输入参数:
*<br>返回类型:
*/
public void loop(){
if (audio!=null)
audio.loop();
}
/**
*<br>方法说明:停止播放声音
*<br>输入参数:
*<br>返回类型:
*/
public void stop(){
if (audio!=null)
audio.stop();
}
}
Applet的代码
<applet CODE = "PlayAudio.class" WIDTH=300 HEIGHT=200 ALIGN=middle > </applet>
import sun.audio.*;
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; }}