以不同的音量同时播放java mp3

时间:2016-03-19 19:29:19

标签: java audio mp3 jlayer

我正在使用JLayer在我的游戏中播放我的声音。我正在尝试为我的音乐(不断播放)和声音效果(零星)设置独立的音量级别。现在我的代码更改了主音量级别,因此,正如预期的那样,它会改变两者的音量。下面是一些示例代码,用于演示我想要做什么(我尝试了很多东西尝试并且像SSCCE一样,并且意识到有一些"错误")。

非常感谢任何帮助。

public static void playSoundOrMusic(String filename, String type) {
    String soundFilename = "";

    if (type.equals("SFX")){
        soundFilename = "res/sounds/sfx/" + filename;
    } else if (type.equals("MUSIC")){
        soundFilename = "res/sounds/music/" + filename;
    }

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(soundFilename);
    } catch (FileNotFoundException e) {
        LOGGER.error("Sound file missing", e);
    }  
    BufferedInputStream bis = new BufferedInputStream(fis);  

    try {
        if (type.equals("SFX")){
            sfxPlayer = new Player(bis);
        } else if (type.equals("MUSIC")){
            musicPlayer = new Player(bis);
        }
    } catch (JavaLayerException e) {
        LOGGER.error("Sound file issue", e);
    } catch (ArrayIndexOutOfBoundsException e) {
        LOGGER.error("Sound file issue", e);
    }

    if (type.equals("SFX")){
        Info source = Port.Info.SPEAKER;
        if (AudioSystem.isLineSupported(source)){   
            try {
                Port outline = (Port) AudioSystem.getLine(source);
                outline.open();                
                FloatControl volumeControl = (FloatControl) outline.getControl(FloatControl.Type.VOLUME);                
                volumeControl.setValue(OptionsJPanel.sfxVolume);
            } catch (LineUnavailableException ex) {
                LOGGER.error("Sound line issue", ex);
            }

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        sfxPlayer.play();
                    } catch (Exception ex) {
                        LOGGER.error("Sound(sfx) playing issue", ex);
                    }
                }
            }).start();
        }
    }

    if (type.equals("MUSIC")){
        Info source = Port.Info.SPEAKER;
        if (AudioSystem.isLineSupported(source)){   
            try {
                Port outline = (Port) AudioSystem.getLine(source);
                outline.open();                
                FloatControl volumeControl = (FloatControl) outline.getControl(FloatControl.Type.VOLUME);                
                volumeControl.setValue(OptionsJPanel.musicVolume);
            } catch (LineUnavailableException ex) {
                LOGGER.error("Sound line issue", ex);
            }

            new Thread(new Runnable() {
                String threadFilename = filename;
                @Override
                public void run() {
                    try {
                        musicPlayer.play();
                        while(!musicPlayer.isComplete()){
                            Thread.currentThread();
                            Thread.sleep(1000);
                        }
                        playSoundOrMusic(threadFilename, type);
                    } catch (Exception ex) {
                        LOGGER.error("Sound(music) playing issue", ex);
                    }
                }
            }).start();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

你有缓冲的输入流:你读它,你操纵数据(减少0.5(50%)),然后你放入一个新流并在第二个播放器中播放。

BufferedInputStream bis = new BufferedInputStream(fis);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte[] data=new byte[1024];
while((k=audioInputStream.read(data, 0, data.length))>-1) {
  for(int i=0; i<k; i++) data[i]=(byte)(0.5*data[i]);
  outputStream.write(data, 0, k);
}   
byte[] audioData=outputStream.toByteArray();
InputStream bis2=new ByteArrayInputStream(outData);    
player2.play(bis2);

-

这是一个将处理和播放文件的类;方法processPlay()可以调整为减少一定比例(0.5),如上所述 - 您可以使用该分数作为参数创建自己的方法。

import javax.sound.sampled.*;
import java.io.*;
import java.net.*;
import javazoom.spi.mpeg.sampled.file.MpegAudioFileReader;

public class QHPlayer {

public void play(String f) {
  int k=0;
  AudioFormat targetFormat=null;
  try {
    AudioInputStream audioInputStream=openFile(f);
    targetFormat=audioInputStream.getFormat();
    byte[] data=new byte[1024];
    DataLine.Info dinfo=new DataLine.Info(SourceDataLine.class, targetFormat);
    SourceDataLine line=null;
      line=(SourceDataLine)AudioSystem.getLine(dinfo);
      if(line!=null) {
        line.open(targetFormat);
        line.start();
        while((k=audioInputStream.read(data, 0, data.length))>-1) {
          line.write(data, 0, k);
        }
        line.stop();
        line.close();
    }
  }
  catch(Exception ex) { ex.printStackTrace(); }
}

public void processPlay(String f) {
  int k=0;
  AudioFormat targetFormat=null;
  ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
  try {
    AudioInputStream audioInputStream=openFile(f);
    targetFormat=audioInputStream.getFormat();
    byte[] data=new byte[1024];

    while((k=audioInputStream.read(data, 0, data.length))>-1)
      outputStream.write(data, 0, k);
    byte[] b=outputStream.toByteArray();
    for(k=0; k<b.length; k++) b[k]=(byte)(0.5*b[k]);


    DataLine.Info dinfo=new DataLine.Info(SourceDataLine.class, targetFormat);
    SourceDataLine line=null;
      line=(SourceDataLine)AudioSystem.getLine(dinfo);
      if(line!=null) {
        line.open(targetFormat);
        line.start();
        System.out.println(line.available());
        k=0;
        while(k<b.length) {
        System.out.println(line.available());
          int i=line.write(b, k, 8*1024);
          k+=i;
        }
        }
        line.stop();
        line.close();
  }
  catch(Exception ex) { ex.printStackTrace(); }
}

public void play(byte[] b) {
  int k=0;
  AudioFormat targetFormat=getAudioFormat();
  try {
    DataLine.Info dinfo=new DataLine.Info(SourceDataLine.class, targetFormat);
    SourceDataLine line=null;
      line=(SourceDataLine)AudioSystem.getLine(dinfo);
      if(line!=null) {
        line.open(targetFormat);
        line.start();
        while(k<b.length) {
          int i=line.write(b, k, 8*1024);
          k+=i;
        }
        line.stop();
        line.close();
    }
  }
  catch(Exception ex) { ex.printStackTrace(); }
}



  public AudioInputStream openFile(String file) {
    AudioInputStream audioInputStream=null;
    try {
      File fileIn = new File(file);
      if(file.endsWith(".mp3"))
        audioInputStream=createMp3(fileIn);
      else
        audioInputStream=AudioSystem.getAudioInputStream(fileIn);
    }
    catch(Exception ex) { ex.printStackTrace(); }
    return audioInputStream;
  }


  AudioInputStream createMp3(File fileIn) throws IOException, Exception {
    AudioInputStream audioInputStream=null;
    AudioFormat targetFormat=null;
    try {
      AudioInputStream in=null;
      MpegAudioFileReader mp=new MpegAudioFileReader();
      in=mp.getAudioInputStream(fileIn);
      AudioFormat baseFormat=in.getFormat();
      targetFormat=new AudioFormat(
              AudioFormat.Encoding.PCM_SIGNED,
              baseFormat.getSampleRate(),
              16,
              baseFormat.getChannels(),
              baseFormat.getChannels() * 2,
              baseFormat.getSampleRate(),
              false);
      audioInputStream=AudioSystem.getAudioInputStream(targetFormat, in);
    }
    catch(UnsupportedAudioFileException ue) { System.out.println("\nUnsupported Audio"); }
    return audioInputStream;
  }


  AudioFormat getAudioFormat() {
    float sampleRate = 44100F;
    int sampleSizeInBits = 16;
    int channels = 2;
    boolean signed = true;
    boolean bigEndian = true;
    return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
  }


  public static void main(String args[]) {
    QHPlayer q=new QHPlayer();
    q.processPlay("c:/.....mp3");
  }

}