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();
}
}
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!");
}
}
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能耗等因素後加以決定。