java中播放声音(一)

此代码可以打开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();
     }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值