Programación de audio en Android pesadilla - soundpool, audiotrack arrghh?
He construido una sencilla aplicación de secuenciador de música para Android que reproduce múltiples archivos de audio.
Originalmente estaba usando SoundPool para reproducir archivos mp3 y funcionó perfectamente en 2.3.4 con un viejo HTC Droid Incredible. Luego lo probé en un Galaxy Nexus con 4.3 y el rendimiento fue horrible. La sincronización de audio en todo el lugar y hubo fallos / clics / pops.
Así que pasé varios días haciendo un reproductor utilizando AudioTrack, incluido un decodificador de mp3, y funcionó perfectamente tanto en el Galaxy como en el HTC. Ahora lo acabo de probar en un Nexus 4 (versión 4.3) y el rendimiento es terrible, el tiempo está por todas partes. SoundPool incluso ofrece un mejor rendimiento en este dispositivo.
Estoy realmente frustrado y no sé qué hacer para terminar mi aplicación, así que realmente apreciaría si alguien pudiera ayudarme. He puesto algunos ejemplos de código de mi reproductor de audio a continuación. He intentado todo lo que puedo pensar, incluyendo cambiar el tamaño del búfer, usandoAudioTrack.MODE_STATIC
¡Los nuevos dispositivos de Google tienen audio de baja latencia, por lo que es muy extraño cómo todo funciona mejor en mi viejo droide!
Gracias por adelantado
/**
* Play note
*/
public void playNote(String note, float vol)
{
PlayThread oldThread = threadMap.get(note);
if(oldThread != null) {
//Cancel timer
if(oldThread.timer != null) {
oldThread.timer.cancel();
oldThread.timer.purge();
oldThread.timer = null;
}
//Stop
oldThread.requestStop();
threadMap.remove(note);
}
//Play if within Polyphony
if(threadMap.size() < POLYPHONY) {
PlayThread thread = new PlayThread(note, vol);
thread.start();
threadMap.put(note, thread);
}
}
/**
* Stop note
*/
public void stopNote(String note, int fadeDurationInMs)
{
PlayThread thread = threadMap.get(note);
if(thread != null) {
thread.fadeOut(fadeDurationInMs);
threadMap.remove(note);
}
}
/**
* Stop all
*/
public void stopAllPlaying(int fadeDurationInMs)
{
for(PlayThread thread : threadMap.values()) {
if(thread != null) {
thread.fadeOut(fadeDurationInMs);
}
}
threadMap.clear();
}
/**
* PlayThread
*/
private class PlayThread extends Thread
{
String note;
float vol;
float fadeVol;
boolean stop;
AudioTrack audioTrack;
Timer timer;
/**
* Constructor
*/
public PlayThread(String note, float vol)
{
super();
this.note = note;
this.vol = vol;
this.fadeVol = vol;
}
/**
* Run
*/
public void run()
{
try {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
//Create buffer
int bufferSize = AudioTrack.getMinBufferSize(SAMPLE_RATE, CHANNELS, AudioFormat.ENCODING_PCM_16BIT);
Log.v(Constants.TAG, "min buffersize = " + bufferSize);
bufferSize = bufferSize * 2;
byte[] buffer = new byte[bufferSize];
//AudioTrack
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLE_RATE, CHANNELS, AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);
audioTrack.setStereoVolume(vol, vol);
audioTrack.play();
//Get byte data
byte[] byteData = sampleMap.get(note);
//Convert to input stream
InputStream input = new ByteArrayInputStream(byteData);
//Write to audioTrack
int bytesRead = 0;
while(!stop && (bytesRead = input.read(buffer)) != -1) {
audioTrack.write(buffer, 0, bytesRead);
}
//When finished...
audioTrack.stop();
audioTrack.release();
input.close();
killThread(this);
}
catch(Exception e) {}
}
/**
* Set volume
*/
private synchronized void setVol(float newVol)
{
audioTrack.setStereoVolume(newVol, newVol);
}
/**
* Update volume
*/
private synchronized void lowerVol()
{
fadeVol -= 0.01;
if(fadeVol < 0) vol = 0;
audioTrack.setStereoVolume(fadeVol, fadeVol);
}
/**
* Fade out
*/
public synchronized void fadeOut(int fadeDurationInMs)
{
//Start decreasing volume
if(fadeDurationInMs > 0) {
timer = new Timer(true);
TimerTask timerTask = new TimerTask()
{
@Override
public void run()
{
//If thread killed while running
try {
//Lower volume
lowerVol();
}
catch (Exception e) {}
//Stop when volume reaches 0
if(fadeVol <= 0) {
if(timer != null) {
timer.cancel();
timer.purge();
}
stop = true;
}
}
};
//Calculate delay, set to 1 if zero
int delay = (int) (fadeDurationInMs / (vol * 100));
if(delay == 0) delay = 1;
timer.schedule(timerTask, delay, delay);
}
}
/**
* Request stop
*/
public synchronized void requestStop()
{
//Stop click/pop when stopping sample
setVol(0.01f);
setVol(0.005f);
stop = true;
}
/**
* Kill Thread
*/
private synchronized void killThread(Thread theThread)
{
if(theThread != null) {
theThread = null;
}
}
}