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

标签 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();
        }
    }
}

最佳答案

您拥有缓冲的输入流:您读取它,操作数据(将值减少 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");
  }

}

关于java - 以不同的音量同时播放 java mp3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36106170/

相关文章:

PHP 获取远程 .mp3 文件的元数据(来自 URL)

java - 在 Intellij 2017.2.4 上使用 Glassfish 4.1.2 时出现问题

java - Java 中的图标 - 如何在面板中添加图标

java - AsyncTask - 如何将对象作为参数传递给匿名 AsyncTask 类

Java 扫描器 useDelimiter() 语法错误

ios - 是否可以在 iPhone 中使用 AVAudioPlayer 更改音频播放速度?

python - 在 python 上运行一些 os-module 代码时,我不断收到 unicode 错误消息(打开 mp3)

.net - 如何在 .NET 中检索 MP3 的持续时间?

python - 如何从 Python 中的字节字符串获取颜色深度和/或分辨率?

android - 以最小延迟播放实时音频流