4

我有一个在屏幕上运行的球的应用程序。当球跑到一半时,应用程序会记录一些音频,计算 FFT 并进行一些额外的分析。

这是由 Asynctask 处理的,但是动画仍然会短暂卡顿。

有人对如何使其运行更顺畅有任何建议吗?

谢谢

下面的代码:

import com.ben.applicationLayer.GameView;
import dataObjectLayer.Sprite;
import dataObjectLayer.MusicalNote;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
import android.media.AudioFormat; 
import android.os.AsyncTask;

public class recorderThread extends AsyncTask<Sprite, Void, Integer> {

short[] audioData;
int bufferSize;    
Sprite ballComp;

@Override
protected Integer doInBackground(Sprite... ball) {

    MusicalNote note = ball[0].expectedNote;
    ballComp = ball[0];
        boolean recorded = false; 
        double frequency;
        int sampleRate = 8192;  
        AudioRecord recorder = instatiateRecorder(sampleRate);
        double[] magnitude = new double[1024];
        double[] audioDataDoubles = new double[2048];

        while (!recorded) {  //loop until recording is running

        if (recorder.getState()==android.media.AudioRecord.STATE_INITIALIZED) 
// check to see if the recorder has initialized yet.
        {
            if (recorder.getRecordingState()==android.media.AudioRecord.RECORDSTATE_STOPPED)
                  recorder.startRecording();  
//check to see if the Recorder has stopped or is not recording, and make it record.                               
            else {             
               double max_index;
               recorder.read(audioData,0,bufferSize);   
//read the PCM audio data into the audioData array

               computeFFT(audioDataDoubles, magnitude);

               max_index = getLargestPeakIndex(magnitude);

               frequency = getFrequencyFromIndex(max_index, sampleRate);

            //checks if correct frequency, assigns number
               int correctNo = correctNumber(frequency, note);

checkIfMultipleNotes(correctNo, max_index, frequency, sampleRate, magnitude, note);

               if (audioDataIsNotEmpty())
                   recorded = true;
               if (correctNo!=1)
                   return correctNo;
              }
        }
        else
        {
            recorded = false;
            recorder = instatiateRecorder(sampleRate);
        }
    }

        if (recorder.getState()==android.media.AudioRecord.RECORDSTATE_RECORDING) 
        {
            killRecorder(recorder);
        }

        return 1;
}


private void killRecorder(AudioRecord recorder) {
    recorder.stop(); //stop the recorder before ending the thread
    recorder.release(); //release the recorders resources
    recorder=null; //set the recorder to be garbage collected
}

@Override
protected void onPostExecute(Integer result) {  
    (result == 2)
        GameView.score++;
    }

private AudioRecord instatiateRecorder(int sampleRate) {    
        bufferSize= AudioRecord.getMinBufferSize(sampleRate,AudioFormat.CHANNEL_CONFIGURATION_MONO,
                AudioFormat.ENCODING_PCM_16BIT)*2;
 //get the buffer size to use with this audio record

AudioRecord recorder = new AudioRecord (AudioSource.MIC,sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,bufferSize); //instantiate the AudioRecorder

    audioData = new short [bufferSize]; //short array that pcm data is put into.         
        return recorder;
}

}
4

3 回答 3

3

使用 Asynctask 符合您想要做的事情。但是,我建议使用线程池。然后,您可以将动画作为任务添加,将音频记录作为任务添加,FFT 作为另一个任务,将附加分析作为任务添加。

短暂的口吃很可能是为动画线程中的录制分配资源的结果。使用池意味着您在创建线程以运行音频任务时不必暂停。显然,一些代码可以方便地完全理解您的问题。

看一眼:

ScheduledThreadPoolExecutor http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

或者

ThreadPoolExecutor http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html

您可能想要做的一个非常简单的例子:

在您的活动中,您可以定义它以启动任务

ExecutorService threadPool = new ScheduledThreadPoolExecutor(2);
Recording record = new Recording();
Ball ball = new Ball(threadPool, record);
threadPool.submit(ball);

Ball.java

import java.util.concurrent.ExecutorService;

public class Ball implements Runnable { 
    private final Recording record;
    private final ExecutorService threadPool;

    private boolean condition;  
    private boolean active;

    public Ball(ExecutorService threadPool, Recording record) {
        this.record = record;
        this.threadPool = threadPool;
        this.active = true;
    }

    @Override public void run() {
        while (this.active) {
            moveBall();
            if (isBallHalfway()) {
                threadPool.submit(record);
            }
        }
    }

    private boolean isBallHalfway() {
        return condition; // Condition for determining when ball is halfway
    }

    private void moveBall() {
        // Code to move the ball
    }
}

录音.java

public class Recording implements Runnable {
    @Override public void run() {
        // Do recording tasks here
    }
}
于 2012-01-25T21:52:13.493 回答
1

正如 Mohammed 所说,不看代码就很难猜出问题所在。考虑到这一点...

听起来您AsyncTask可能正在阻止其他线程执行。确保您Thread.sleep()在那里有一些调用,以使调度程序有机会切换回 UI 线程(Thread.yield()也是一种选择,但请注意有一些收益问题)。

于 2012-01-26T10:46:58.373 回答
0

没有代码很难猜测可以优化,但我会告诉你我在加载超过 100 万次操作时做了什么.. • 如果你有性能问题,请尝试: 1-检查变量的数据类型并设置如果您确定变量不需要更多字节,则较低,即对于您的大小而不是 int。

2-检查您的代码并尝试获取所有结果可以存储以供下次启动,并在下次调用它们而不是再次计算它们。

• 但是如果你的问题是动画慢而且你的记忆力没有问题,那么试着减少动画的周期或者增加动作的单位。

顺便问一下,你是如何实现动画的?逐帧动画,或布局动画,或视图动画?

于 2012-01-25T21:25:52.450 回答