assetsフォルダに置いた16Bit StereoのリニアPCMファイルを鳴らすコード的なもの。
class PlayThread extends Thread {
byte[] pcmData;
AudioTrack audioTrack;
float maxVolume ;
float minVolume;
PlayThread(String filename) {
setPcmData(filename);
makeAudioTrack();
maxVolume = AudioTrack.getMaxVolume();
minVolume = AudioTrack.getMinVolume();
}
public void run() {
if (audioTrack != null) {
int result= audioTrack.setLoopPoints(0, pcmData.length/4, -1);
if (result != AudioTrack.SUCCESS) {
System.out.println("result="+result+"pcmData.length="+ pcmData.length);
}
audioTrack.write(pcmData, 0, pcmData.length);
audioTrack.play();
}
}
void makeAudioTrack() {
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
AudioFormat.ENCODING_PCM_16BIT, pcmData.length,
AudioTrack.MODE_STATIC);
}
void playStop() {
if (audioTrack.getPlayState() == AudioTrack.PLAYSTATE_PLAYING) {
audioTrack.stop();
audioTrack.release();
}
}
void setStereoVolume(int left,int right) {
float leftF = minVolume+(maxVolume-minVolume)*left/100;
float rightF = minVolume+(maxVolume-minVolume)*right/100;
audioTrack.setStereoVolume(leftF, rightF);
}
void setPcmData(String s) {
AssetManager as = getResources().getAssets();
AssetFileDescriptor afd = null;
try {
afd = as.openFd (s);
} catch (IOException e) {
e.printStackTrace();
}
if (afd != null) {
pcmData = new byte[(int)afd.getLength()];
InputStream is = null;
try {
is = afd.createInputStream();
is.read(pcmData);
} catch (IOException e) {
e.printStackTrace();
}finally {
IOUtils.closeQuietly(is);
}
}else {
finish();
}
}
}
}