JOAL学习笔记 第八课 OggVorbis格式流

JOAL学习笔记

 

如果将之前实例代码中的错误数量比作毛毛雨的话,笔者已经让本次课程的大暴雨淋成落汤鸡了……


由于本次课程中原文作者并未给出完整的代码片,也并未给出解码器的实现,因此我在这里把我已经调通的测试代码贴出来。

先贴出一张图,这样能让大家对整个实现的体系有所了解:

可以看出,我并没有选择教程建议的j-ogg.de提供的j-oggAPI,这个德国网站上并没有实例的讲解,仅仅提供了一个API文档,我参照这个文档(英文)写了一些测试代码,发现其内部报了一个数组越界错误,估计这套API应该是有Bug的。

 

除了这个原因外,选择Java Sound API作为解码器核心的另一个理由,是对于mp3、ogg等格式已经存在较为成熟的SPI组件,我们无需显示地调用使用哪种解码器,JavaSound会自动找到系统内支持解码的服务,这样对于不同格式的文件可以通用一套API。

 

最后贴代码之前,先把依赖项来源给出,这次的依赖项很多:

Jlayer:http://www.javazoom.net/javalayer/javalayer.html

mp3SPI:http://www.javazoom.net/mp3spi/mp3spi.html

oggvorbisSPI:http://www.javazoom.net/vorbisspi/vorbisspi.html

jorbis:http://www.jcraft.com/jorbis/ 这是oggSPI的依赖项

项目示意图:

jcraft的资源下载下来是没编译的,需要自己加入项目中,这点请注意。


源代码:

Main.java:

package com.thrblock.openal;

import com.jogamp.openal.ALFactory;
import com.jogamp.openal.util.ALut;

public class Main {
	public static void main(String[] args) {
		ALut.alutInit();
		OggVorbisPlayer player = new OggVorbisPlayer(ALFactory.getAL(),"./oggData/ThorVariation.ogg");
		//OggVorbisPlayer player = new OggVorbisPlayer(ALFactory.getAL(),"./mp3Data/009.mp3");
		//OggVorbisPlayer player = new OggVorbisPlayer(ALFactory.getAL(),"./wavData/0201.wav");
		player.open();
		player.playstream();
		player.release();
	}
}


OggDecoder.java:

package com.thrblock.openal;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

public class OggDecoder {
	private boolean inited = false;
	private AudioFormat baseFormat, decodedFormat;
	private AudioInputStream audioInputStream, decodedAudioInputStream;

	public OggDecoder(String fileName) {
		try {

			File file = new File(fileName);
			audioInputStream = AudioSystem.getAudioInputStream(file);
			baseFormat = audioInputStream.getFormat();
			
			decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
					baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
					baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
					false);
			
			decodedAudioInputStream = AudioSystem.getAudioInputStream(
					decodedFormat, audioInputStream);
			inited = true;
		} catch (IOException | UnsupportedAudioFileException e) {
			if (e instanceof UnsupportedAudioFileException) {
				System.out.println("UnSupport File!");
			}
			System.out.println("Error in load Ogg File");
		}
	}

	public boolean initialize() {
		return inited;
	}

	public int numChannels() {
		return decodedFormat.getChannels();
	}

	public float sampleRate() {
		return decodedFormat.getSampleRate();
	}

	public int read(byte[] pcm) throws IOException {
		return decodedAudioInputStream.read(pcm, 0, pcm.length);
	}

	public void dump() {
		System.out.println("dump!");
	}
}


OggVorbisPlayer.java:
package com.thrblock.openal;

import java.nio.ByteBuffer;
import java.util.Arrays;

import com.jogamp.openal.AL;

public class OggVorbisPlayer {
	// 区块大小是我们每次希望由流中读取的数据数量。
	private static int BUFFER_SIZE = 4096 * 8;
	// 音频管线中需要使用的缓冲区数量
	private static int NUM_BUFFERS = 4;

	// 容纳声音数据的缓冲区.默认两个 (前缓冲区/后缓冲区)
	private int[] buffers = new int[NUM_BUFFERS];

	// 发出声音的声源
	private int[] source = new int[1];

	static float[] sourcePos = { 0.0f, 0.0f, 0.0f };
	static float[] sourceVel = { 0.0f, 0.0f, 0.0f };
	static float[] sourceDir = { 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f };

	static float[] listenerPos = { 0.0f, 0.0f, 0.0f };
	static float[] listenerVel = { 0.0f, 0.0f, 0.0f };
	// 解码器
	private OggDecoder oggDecoder;
	private int format;
	private float rate;
	
	private AL al;
	private String url;
	public OggVorbisPlayer(AL al,String url) {
		this.al = al;
		this.url = url;
	}

	/**
	 * 初始化并播放流的主循环
	 */
	public boolean playstream() {
		if (!open())
			return false;

		//oggDecoder.dump();
		if (!playback())
			return false;

		System.out.println("Playing!");
		while (update()) {
			if (playing()){
				try {Thread.sleep(10);} catch (InterruptedException e) {}
				continue;
			}
			//System.out.println("Not Playing!");
			if (!playback())
				return false;
		}

		return true;

	}

	/**
	 * 打开Ogg流,并依据流的属性初始化OpenAL
	 */
	public boolean open() {
		oggDecoder = new OggDecoder(url);

		if (!oggDecoder.initialize()) {
			System.err.println("Error initializing stream...");
			return false;
		}

		if (oggDecoder.numChannels() == 1) {
			format = AL.AL_FORMAT_MONO16;
		} else {
			format = AL.AL_FORMAT_STEREO16;
		}

		rate = oggDecoder.sampleRate();

		al.alGenBuffers(NUM_BUFFERS, buffers, 0);
		check("Open_1");
		al.alGenSources(1, source, 0);
		check("Open_2");

		al.alSourcefv(source[0], AL.AL_POSITION, sourcePos, 0);
		al.alSourcefv(source[0], AL.AL_VELOCITY, sourceVel, 0);
		al.alSourcefv(source[0], AL.AL_DIRECTION, sourceDir, 0);

		al.alSourcef(source[0], AL.AL_ROLLOFF_FACTOR, 0.0f);
		al.alSourcei(source[0], AL.AL_SOURCE_RELATIVE, AL.AL_TRUE);

		return true;
	}

	/**
	 * 清理OpenAL的过程
	 */
	public void release() {
		al.alSourceStop(source[0]);
		empty();

		for (int i = 0; i < NUM_BUFFERS; i++) {
			al.alDeleteSources(i, source, 0);
			check("Release_1");
		}
	}

	/**
	 * 播放Ogg流
	 */
	private boolean playback() {
		if (playing())
			return true;

		for (int i = 0; i < NUM_BUFFERS; i++) {
			if (!stream(buffers[i]))
				return false;
		}
		check("playback_1");
		al.alSourceQueueBuffers(source[0], NUM_BUFFERS, buffers, 0);
		check("playback_2");
		al.alSourcePlay(source[0]);
		check("playback_3");
		return true;

	}

	/**
	 * 检测当前是否处于播放当中
	 */
	private boolean playing() {
		int[] state = new int[1];

		al.alGetSourcei(source[0], AL.AL_SOURCE_STATE, state, 0);

		return (state[0] == AL.AL_PLAYING);

	}

	/**
	 * 如果需要,将流的下一部分读入缓冲区
	 */
	private boolean update() {
		int[] processed = new int[1];
		boolean active = true;

		al.alGetSourcei(source[0], AL.AL_BUFFERS_PROCESSED, processed, 0);

		while (processed[0] > 0) {
			int[] buffer = new int[1];

			al.alSourceUnqueueBuffers(source[0], 1, buffer, 0);
			check("Update_1");

			active = stream(buffer[0]);

			al.alSourceQueueBuffers(source[0], 1, buffer, 0);
			check("Update_2");

			processed[0]--;
		}

		return active;

	}

	/**
	 * 重新装载缓冲区 (读入下一个区块)
	 */
	byte[] pcm = new byte[BUFFER_SIZE];
	ByteBuffer data = ByteBuffer.wrap(pcm, 0, pcm.length);
	private boolean stream(int buffer) {
		int size = 0;

		try {
			Arrays.fill(pcm, (byte)0);
			while ((size = oggDecoder.read(pcm)) == 0);
			if(size < 0){
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		if(size > 0){
			al.alBufferData(buffer, format, data, size, (int) rate);	
		}
		check("Stream_1" + buffer);

		return true;

	}

	/**
	 * 清空队列
	 */
	private void empty() {
		int[] queued = new int[1];

		al.alGetSourcei(source[0], AL.AL_BUFFERS_QUEUED, queued, 0);

		while (queued[0] > 0) {
			int[] buffer = new int[1];

			al.alSourceUnqueueBuffers(source[0], 1, buffer, 0);
			check("Empty_1");

			queued[0]--;
		}

		oggDecoder = null;

	}

	private void check(String flag) {
		int tmp;
		if ((tmp = al.alGetError()) != AL.AL_NO_ERROR) {
			System.out.println(getALErrorString(tmp)+",Error," + flag);
		}
	}
	private String getALErrorString(int err) {
		switch (err) {
		case AL.AL_NO_ERROR:
			return "AL_NO_ERROR";
		case AL.AL_INVALID_NAME:
			return "AL_INVALID_NAME";
		case AL.AL_INVALID_ENUM:
			return "AL_INVALID_ENUM";
		case AL.AL_INVALID_VALUE:
			return "AL_INVALID_VALUE";
		case AL.AL_INVALID_OPERATION:
			return "AL_INVALID_OPERATION";
		case AL.AL_OUT_OF_MEMORY:
			return "AL_OUT_OF_MEMORY";
		default:
			return null;
		}
	}
	
}

本次需要注意的问题:

 

首先,我不知道是不是因为我用JavaSound + SPI这种解码方式导致的问题,Ogg的流有时会读出0个字节,此时文件并未结束。经过研究发现这个数值是合法的(直接写入javax的sourceDataLine可以正确播放出ogg音频),因此对于填装缓冲区时,一定要等到数据出来在填装,填装长度为0在OpenAL中是非法的。这里可以参考上面stream方法相对于原文中的改动。


其次,在使用al.alBufferData后,JVM中的byte[]组数据已经被填充到OpenAL层次,因此其数组可以再利用,不需要每次new。


最后我想说说对于update调用频率的看法。

由于需要对缓冲区队列进行管理,我们不得不分出一条线程来做这些事,也就是我们文中的update方法及其循环结构;原文中如果不出意外的话,update会以可能的最大频率进行调用,这将会直接占满CPU的一个核心或者支持超线程CPU的一条线,而这样的好处是对于播放的控制(如暂停、停止、继续等)响应最快。

此时,如果加入一点阻塞延迟的话,例如sleep(1),会大大降低CPU占用,1ms对于CPU来讲已经休息的足够了。但阻塞的加入会影响到控制的响应时间,该时间以阻塞时间为上限。

笔者认为,在大部分情况下,对于音乐播放的控制需求响应不会太高,例如在下达停止播放的命令后,立即停止与延时1ms停止对于人来讲差别不大,因此,适当的阻塞是必要的。

如果阻塞时间过长,还会导致另一个情况,缓冲区数据播放完毕而没有再填装,此时音乐会有明显的播放卡顿。

 

所以阻塞时间需要权衡缓冲区大小、响应时间需求、CPU能耗等因素后加以决定。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章