对声音媒体的直接支持可以说是Java的一大特色,尤其是在动画中配上声音效果,就可以使人在视觉上和听觉上均得到美的享受,那才叫过瘾。Java中播放声音文件与显示图像文件一样方便,同样只需要先将声音文件装载进来,然后播放就行了。
Java目前支持的声音文件只有一种格式,那就是SUN公司的AU格式(AU文件),也称为u-law格式。由于AU格式的声音仅有8KHz的采样频率且不支持立体声效果,所以音质不算太好。唯一的好处就是AU声音文件的尺寸比其它格式小,有利于网上传输。一般,我们较熟悉的大都是WAV格式的声音文件,因此必须先将它们转换为AU格式(可以选用Goldwave软件来进行这种格式转换)。
声音文件准备好以后,就可以考虑将它装载进来并播放。在Applet类中提供的play( )方法可以将声音文件的装载与播放一并完成,其调用格式如下:
void play(URL url)
void play(URL url, String name)
可见,play( )方法的调用格式与getImage( )方法是完全一样的,也采用URL来定位声音文件。例如,某声音文件audioau与applet文件存放在同一目录下,可以这样写:
play(getCodeBase( ),"audioau");
一旦play( )方法装载了该声音文件,就立即播放。如果找不到指定URL下的声音文件,play( )方法不返回出错信息,只是听不到想听的声音而已。
由于play( )方法只能将声音播放一遍,若想循环播放某声音作为背景音乐,就需要用到功能更强大的AudioClip类,它能更有效地管理声音的播放 *** 作。因为它被定义在javaapplet程序包中,所以使用该类的话,不要忘了在程序头部加上:
import javaappletAudioClip;
为了得到AudioClip对象,我们可以调用Applet类中的getAudioClip( )方法。它能装载指定URL的声音文件,并返回一个AudioClip对象,其调用格式如下:
AudioClip getAudioClip(URL url)
AudioClip getAudioClip(URL url, String name)
得到AudioClip对象以后,就可以调用AudioClip类中所提供的各种方法来 *** 作其中的声音数据,这些方法如表4-4所示。
如果getAudioClip( )方法没有找到所指定的声音文件,就会返回null值。所以,在调用表4-4中所列的方法前,应该先检查一下得到的AudioClip对象不是null,因为在null对象上调用上述方法将导致出错。
如果需要的话,我们还可以在applet中同时装载几个声音文件来一起播放,到时候,这些声音将混合在一起,就象二重奏一样。另外还有一点要说明的是,如果我们使用AudioClip对象的loop( )方法来重复播放背景音乐时,千万不要忘记在适当的时候调用AudioClip对象的stop( )方法来结束放音,否则的话,即使用户离开这一Web页面,该声音也不会停止,这无疑将会惹恼用户。因此,一般我们都在applet的stop( )方法中添上停止播放的代码。
例如,下面这段程序将播放两段声音,一段是连续播放的背景音乐,另一段是讲话录音。
import javaappletAudioClip;
public class Audios extends javaappletApplet{
AudioClip bgmusic,speak;
public void init(){
bgmusic=getAudioClip(getDocumentBase(),"spaceau");
speak=getAudioClip(getDocumentBase(),"introau");
}
public void start(){
if(bgmusic!=null)
bgmusicloop();
if(speak!=null)
speakplay();
}
public void stop(){
if(bgmusic!=null)
bgmusicstop(); //关闭背景音乐,切记。
}
}
package comhongyuantest;
import javaioFile;
import javaioIOException;
import javaxsoundsampledAudioFormat;
import
javaxsoundsampledAudioInputStream;
import
javaxsoundsampledAudioSystem;
import
javaxsoundsampledDataLine;
import
javaxsoundsampledLineUnavailableException;
import
javaxsoundsampledSourceDataLine;
import
javaxsoundsampledUnsupportedAudioFileException;
public class MusicTest {
public static final String MUSIC_FILE = "相逢一笑wav";
public static void main(String[] args) throws
LineUnavailableException,
UnsupportedAudioFileException, IOException {
// 获取音频输入流
AudioInputStream audioInputStream =
AudioSystem
getAudioInputStream(new File(MUSIC_FILE));
//
获取音频编码对象
AudioFormat audioFormat = audioInputStreamgetFormat();
// 设置数据输入
DataLineInfo dataLineInfo = new
DataLineInfo(SourceDataLineclass,
audioFormat,
AudioSystemNOT_SPECIFIED);
SourceDataLine sourceDataLine =
(SourceDataLine)
AudioSystem
getLine(dataLineInfo);
sourceDataLineopen(audioFormat);
sourceDataLinestart();
/
从输入流中读取数据发送到混音器
/
int count;
byte tempBuffer[]
= new byte[1024];
while ((count = audioInputStreamread(tempBuffer, 0,
tempBufferlength)) != -1) {
if (count > 0)
{
sourceDataLinewrite(tempBuffer, 0, count);
}
}
//
清空数据缓冲,并关闭输入
sourceDataLinedrain();
sourceDataLineclose();
}
}
生成 wav,然后网页中嵌入
请参考生成wave的C#代码
/// <summary>
/// 输出WAV
/// </summary>
/// <param name="path">保存路径</param>
/// <param name="str">要转换的文本内容</param>
/// <returns></returns>
public bool WreiteToWAV(string path,string str,SpeechAudioFormatType SpAudioType)
{
SpeechStreamFileMode SpFileMode = SpeechStreamFileModeSSFMCreateForWrite;
SpFileStream SpFileStream = new SpFileStream();
SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlagsSVSFlagsAsync;
SpAudioFormat SpAudio = new DotNetSpeechSpAudioFormat();
SpAudioType = SpAudioType;
SpFileStreamFormat = SpAudio;
SpFileStreamOpen(path, SpFileMode, false);
voiceAudioOutputStream = SpFileStream;
voiceSpeak(str, SpFlags);
voiceWaitUntilDone(TimeoutInfinite);
SpFileStreamClose();
return FileExists(path);
}
主要的功能模块在两个程序包中提供:
javaxmediasoundsampled-该程序包明确地说明了捕获、混合以及回播数字采样音频的界面。
javaxmediasoundMIDI-该程序包提供MIDI合成、序列化以及事件传送的界面。
代码如下;
import javaio; import javaxsoundsampled; import javanet; / Title: VoiceChat Description: 输出音频(放音程序) Copyright: Copyright (c) 2001 Company: @author 你猜! @version 10 / class Playback implements Runnable { final int bufSize = 16384; SourceDataLine line; Thread thread; Socket s; Playback(Socket s){//构造器 取得socket以获得网络输入流 thiss=s; }
public void start()
代码和详细解释太长,你给个邮箱,我给你发过去
package mp3;
import javaioFile;
import javaioFileNotFoundException;
import javaioIOException;
import javaioRandomAccessFile;
public class ReadMp3 {
private SongInfo info = null;
private RandomAccessFile ran = null;
private File file = null;
public ReadMp3() throws FileNotFoundException {
file = new File("/rec/感觉不到你mp3");
ran = new RandomAccessFile(file, "r");
Systemoutprintln("文件装载完毕");
}
public static void main(String[] args) throws IOException {
ReadMp3 read = new ReadMp3();
byte[] buffer = new byte[128];
readranseek(readranlength() - 128);
readranread(buffer);
SongInfo info = new SongInfo(buffer);
Systemoutprintln("name:" + infogetSongName() + " year:"
+ infogetYear() + " 歌手:" + infogetArtist() + " 专辑名:"
+ infogetAlbum() + " 备注:" + infogetComment());
}
}
package mp3;
/
一个歌曲信息的类的结构表示 这个歌曲是使用ID3V1的信息存储结构的
@author hadeslee
/
public class SongInfo {
private final String TAG = "TAG"; // 文件头1-3
private String songName; // 歌曲名4-33
private String artist; // 歌手名34-63
private String album; // 专辑名61-93
private String year; // 年94-97
private String comment; // 备注98-125
private byte r1, r2, r3; // 三个保留位126,127,128
private boolean valid; // 是否合法
public transient String fileName; // 此歌曲对应的文件名,没有封装
public SongInfo(byte[] data) {
if (datalength != 128) {
throw new RuntimeException("数据长度不合法:" + datalength);
}
String tag = new String(data, 0, 3);
// 只有前三个字节是TAG才处理后面的字节
if (tagequalsIgnoreCase("TAG")) {
valid = true;
songName = new String(data, 3, 30)trim();
artist = new String(data, 33, 30)trim();
album = new String(data, 63, 30)trim();
year = new String(data, 93, 4)trim();
comment = new String(data, 97, 28)trim();
r1 = data[125];
r2 = data[126];
r3 = data[127];
} else {
valid = false;
}
}
public SongInfo() {
}
/
返回是否合法
@return 是否
/
public boolean isValid() {
return valid;
}
/
得到此对象的128个字节的表示形式
@return
/
public byte[] getBytes() {
byte[] data = new byte[128];
Systemarraycopy(TAGgetBytes(), 0, data, 0, 3);
byte[] temp = songNamegetBytes();
Systemarraycopy(temp, 0, data, 3, templength > 30 30 : templength);
temp = artistgetBytes();
System
arraycopy(temp, 0, data, 33, templength > 30 30
: templength);
temp = albumgetBytes();
System
arraycopy(temp, 0, data, 63, templength > 30 30
: templength);
temp = yeargetBytes();
Systemarraycopy(temp, 0, data, 93, templength > 4 4 : templength);
temp = commentgetBytes();
System
arraycopy(temp, 0, data, 97, templength > 28 28
: templength);
data[125] = r1;
data[126] = r2;
data[127] = r3;
return data;
}
public String getArtist() {
return artist;
}
public void setArtist(String authorName) {
thisartist = authorName;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
thiscomment = comment;
}
public byte getR1() {
return r1;
}
public void setR1(byte r1) {
thisr1 = r1;
}
public byte getR2() {
return r2;
}
public void setR2(byte r2) {
thisr2 = r2;
}
public byte getR3() {
return r3;
}
public void setR3(byte r3) {
thisr3 = r3;
}
public String getSongName() {
return songName;
}
public void setSongName(String songName) {
if (songName == null) {
throw new NullPointerException("歌名不能是null!");
}
valid = true;
thissongName = songName;
}
public String getAlbum() {
return album;
}
public void setAlbum(String specialName) {
thisalbum = specialName;
}
public String getYear() {
return year;
}
public void setYear(String year) {
thisyear = year;
}
}
public class Test {
public static void main(String[] args) {
File file = new File("c:/我的文档/音乐");
File[] files = filelistFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
int i = namelastIndexOf("");
name = namesubstring(i);
if (nameequalsIgnoreCase("flv"))//根据格式自己判断
return true;
else
return false;
}
});
List<File> list =new ArrayList<File>();
for (int i = 0; i < fileslength; i++) {
File f = new File(filegetAbsolutePath() + "/" + files[i]getName());
listadd(f);
Systemoutprintln(fgetName());
}
}
}//播放器 自己找找看 有了file 就好办了吧
直接下个JMF,google搜,sun官网上有~~然后安装目录是你的JDK,
再播放MP3文件就:
import javaxmedia;
import javanetMalformedURLException;
import javanetURL;
Player player;
File playFile=new File("");//你的MP3文件
try {
player=ManagercreateRealizedPlayer(playFiletoURL());
playerprefetch();
playersetMediaTime(new Time(100));
playerstart();
} catch (NoPlayerException e1)
{
e1printStackTrace();
} catch (CannotRealizeException e1)
{
e1printStackTrace();
} catch (MalformedURLException e1)
{
e1printStackTrace();
} catch (IOException e1)
{
e1printStackTrace();
}
这种基本代码,自己搜一下,用编译器熟悉熟悉JMF的方法就会了。。。我以前回答别人时的答案~~~
以上就是关于java如何播放声音全部的内容,包括:java如何播放声音、java web jacob 调用微软语音库获取音频流、通过输入设备获取音频流 原理或java实现等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)