Java Sound API,格式转换

转换音频格式本以为java很难实现,但是发现Java sound Api还是比较强大的,它可以读取音频设备输入,播放音频,还能进行音频格式转换,当然,这种转换不是所有的格式都支持,下面代码将音频格式从8bit 8k pcm wav转换为16bit 8k pcm wav。

this code show how to convert audio from 8bit 8k pcm to 16 bit 8k pcm in pure java:

	public static void convert(InputStream in, OutputStream out) throws IOException, UnsupportedAudioFileException
	{

		// get an AudioInputStream of the desired format for playback
		AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
		float rate = 8000f;
		int targetSampleSize = 16;
		boolean bigEndian = true;
		int channels = 1;
//		AudioFormat sourceFormat = new AudioFormat(encoding, rate, sourceSampleSize, channels, (sourceSampleSize / 8)
//				* channels, rate, bigEndian);
		AudioFormat targetFormat = new AudioFormat(encoding, rate, targetSampleSize, channels, (targetSampleSize / 8)
				* channels, rate, bigEndian);

		AudioInputStream lowResAIS = AudioSystem.getAudioInputStream(in); 
		AudioFormat sourceFormat = lowResAIS.getFormat();
		if (AudioSystem.isConversionSupported(targetFormat, sourceFormat))
		{
			lowResAIS = AudioSystem.getAudioInputStream(targetFormat, lowResAIS);
		}
		else
		{
			throw new UnsupportedAudioFileException("not supported!");
		}

		AudioSystem.write(lowResAIS, AudioFileFormat.Type.WAVE, out);
	}

这种转换跨度不大,其他的参考 http://www.oracle.com/technetwork/java/javase/sound-dev-guide-1-159173.pdf


Total views.

© 2013 - 2018. All rights reserved.

Powered by Hydejack v6.6.1