简体   繁体   English

在Java中使用.wav格式循环播放音频文件

[英]Loop audio files using .wav format in java

i am trying to loop an audio file but when i've tried the other various methods available, my music doesn't play. 我正在尝试循环播放音频文件,但是当我尝试其他可用方法时,我的音乐无法播放。

My basic code is: 我的基本代码是:

import java.io.*;
import sun.audio.*;

public class PlayMusic {


    public void playSound() {
        try {
            AudioPlayer p = AudioPlayer.player;
            AudioStream as = new AudioStream(new FileInputStream("02 River Flows In You.wav"));
            p.start(as);


        } catch (IOException IOE) {
        }
    }

I've never seen sun.audio.AudioPlayer in use before! 我从未见过使用过sun.audio.AudioPlayer! I've always used the javax.sound.sampled library. 我一直使用javax.sound.sampled库。

Maybe you can tell me how you came across it. 也许你可以告诉我你是怎么遇到的。 It looks to me like rather old code (10 years?) and also a bit on the limited side. 在我看来,它看起来像是比较旧的代码(10年?),而且在有限的方面也有点。

I think, if you aren't getting a single playback, you should try the URL form: 我认为,如果您没有一次播放,则应尝试使用URL形式:

AudioStream audiostream = new AudioStream(url.openStream());
     AudioPlayer.player.start(audiostream);

Then try putting the code in a loop? 然后尝试将代码循环? A lot depends on whether the .start command blocks or not. 在很大程度上取决于.start命令是否阻塞。 If it launches a separate thread (most likely), then you will have to figure out when the file ends, and I don't see any commands provided to do that! 如果它启动一个单独的线程(最有可能),那么您将不得不弄清楚文件何时结束,而且我看不到提供任何执行此操作的命令! The spec also lists the possibility of creating an ContinuousAudioDataStream and managing that. 该规范还列出了创建ContinuousAudioDataStream并进行管理的可能性。

Unless there is something I don't know about this library that I should, I recommend using either a javax.sound.sampled.Clip, or javax.sound.sampled.SourceDataLine for playback. 除非我对该库不了解,否则建议使用javax.sound.sampled.Clip或javax.sound.sampled.SourceDataLine进行播放。 The Clip has a boolean you can set for looping, but requires the entire file be loaded into memory first. 剪辑具有可设置为循环的布尔值,但需要先将整个文件加载到内存中。 The SourceDataLine plays back from a url or file location, and can implement a listener to tell you when the file is done. SourceDataLine从URL或文件位置播放,并且可以实现一个侦听器来告诉您文件何时完成。

http://docs.oracle.com/javase/tutorial/sound/playing.html http://docs.oracle.com/javase/tutorial/sound/playing.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM