DR.HTML
دوشنبه 04 آبان 1394, 09:26 صبح
سلام دوستان من میخخوام یک کلاس بنویسم برای پخش فایل های صوتی شمال mp3 و ...
کسی مثالی برای یا تکه کدی برای مثال داره با تشکر
DR.HTML
دوشنبه 04 آبان 1394, 18:10 عصر
دوستان کسی نیمتونه راهنمایی کنه ؟
ahmad.mo74
پنج شنبه 07 آبان 1394, 21:26 عصر
سلام
باید از لایبرری mp3spi (http://www.javazoom.net/mp3spi/mp3spi.html) استفاده کنید.
اگر از maven استفاده میکنید این رو به dependency ها اضافش کنید :
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>mp3spi</artifactId>
<version>1.9.5-1</version>
</dependency>
کدی که برای پخش صوت باید استفاده کنید :
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author ahmad
*/
public final class AudioPlayer {
private static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
private final AtomicBoolean playing = new AtomicBoolean();
public boolean play(InputStream inputStream) throws IOException, UnsupportedAudioFileException, LineUnavailableException {
try (AudioInputStream ais = AudioSystem.getAudioInputStream(inputStream)) {
return play(ais);
}
}
public boolean play(URL url) throws IOException, UnsupportedAudioFileException, LineUnavailableException {
try (AudioInputStream ais = AudioSystem.getAudioInputStream(url)) {
return play(ais);
}
}
public boolean play(File file) throws IOException, UnsupportedAudioFileException, LineUnavailableException {
try (AudioInputStream ais = AudioSystem.getAudioInputStream(file)) {
return play(ais);
}
}
public boolean play(AudioInputStream ais) throws IOException, LineUnavailableException {
if (!playing.compareAndSet(false, true)) {
return false;
}
AudioFormat baseFormat = ais.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
true);
try (AudioInputStream decodedAis = AudioSystem.getAudioInputStream(decodedFormat, ais);
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(new DataLine.Info(SourceDataLine.class, decodedFormat))) {
line.open(decodedFormat);
line.start();
int read;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
while (playing.get() && (read = decodedAis.read(buffer)) != -1) {
line.write(buffer, 0, read);
}
line.drain();
line.stop();
} finally {
playing.set(false);
}
return true;
}
public boolean stop() {
return playing.compareAndSet(true, false);
}
public static void main(String[] args) throws Exception {
AudioPlayer player = new AudioPlayer();
URL url = new URL("http://dn.newmp3mad.com/128-427869/Tum%20Hi%20Ho.mp3");
player.play(url);
}
}
vBulletin® v4.2.5, Copyright ©2000-1404, Jelsoft Enterprises Ltd.