六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 67|回复: 0

java中播放声音(一)

[复制链接]

升级  82.67%

50

主题

50

主题

50

主题

秀才

Rank: 2

积分
174
 楼主| 发表于 2013-1-27 05:18:11 | 显示全部楼层 |阅读模式
此代码可以打开AudioFormat 为PCM_SIGNED, 11025.0 Hz, 16 bit的wav后缀文件,大家可以参考以下代码

import javax.sound.sampled.*;
import java.io.File;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;
class SecondTest {
    public static void loadSound() {
        try {
           String  audiofile=  "c:\\audio\\system.wav";
            // From file
            AudioInputStream stream = AudioSystem.getAudioInputStream(new File(
                    audiofile));
            // From URL
//            AudioInputStream stream = AudioSystem.getAudioInputStream(new URL(
//                    "http://192.168.254.102:8888/oaapp/1-welcome.wav"));
            // At present, ALAW and ULAW encodings must be converted
            // to PCM_SIGNED before it can be played
            AudioFormat format = stream.getFormat();
            if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
                format = new AudioFormat(
                        AudioFormat.Encoding.PCM_SIGNED,
                        format.getSampleRate(),
                        format.getSampleSizeInBits() * 2,
                        format.getChannels(),
                        format.getFrameSize() * 2,
                        format.getFrameRate(),
                        true); // big endian
                stream = AudioSystem.getAudioInputStream(format, stream);
            }
            // Create the clip
            DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(),
                    ((int) stream.getFrameLength() * format.getFrameSize()));
            Clip clip = (Clip) AudioSystem.getLine(info);
            // This method does not return until the audio file is completely loaded
            clip.open(stream);
            // Start playing
            clip.start();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {e.printStackTrace();
        } catch (LineUnavailableException e) {e.printStackTrace();
        } catch (UnsupportedAudioFileException e) {e.printStackTrace();
        }
    }
     public static void main(String args[]) {
      loadSound();
     }
}
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表