I'm trying to play a song snippet in an Android app which includes a camera preview. But whenever I start a song playing with
MediaPlayer mp = MediaPlayer.create(this, R.raw.song1);
mp.start();
It always stops after ~.5seconds
I have come to the conclusion that it is something about the camera preview that is stopping the music, since I put the above code snippet in OnCreate and it played for about 2 seconds, then stopped immediately after the camera preview appeared on the screen. I have a suspicion that this may be related to the autofocus.
Below is the code for the camera initialization, preview and surface callbacks in this app:
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
{
if (mCamera == null)
return;
//Determine whether our preview should be portrait or landscape, and set our parameters accordingly
//TODO Fix this for the N1
mCamera.setDisplayOrientation(90);
//Tell the camera to use our surfaceholder and start preview
try
{
mCamera.setPreviewDisplay(holder);
}
catch (IOException e)
{
e.printStackTrace();
}
mStartPreviewHandler.post(mStartPreview);
}
private void initializeCamera()
{
mCamera = Camera.open();
Parameters params = mCamera.getParameters();
//Save the pixel format used in preview. This will be passed to the Reader.
mPixelFormat = params.getPreviewFormat();
//Commit parameter changes
mCamera.setParameters(params);
mCounter = 0;
}
private Camera.AutoFocusCallback mAutofocusCallback = new Camera.AutoFocusCallback()
{
@Override
public void onAutoFocus(boolean success, Camera camera)
{
//Restart autofocus
mAutoFocusHandler.postDelayed(mUpdateAutofocus, mAutoFocusDelay);
}
};
//Runnable to start the auto focus cycle
final Runnable mUpdateAutofocus = new Runnable()
{
public void run()
{
startAutofocus();
}
};
private void startAutofocus()
{
if (mCamera == null)
return;
mCamera.autoFocus(mAutofocusCallback);
}
private Camera.PreviewCallback mPreviewCallback = new Camera.PreviewCallback()
{
@Override
public void onPreviewFrame(byte[] data, Camera camera)
{
if (mCamera == null)
{
return;
}
if (mCounter == 0)//Start the autofocus cycle on the first preview frame
{
mAutoFocusHandler.post(mUpdateAutofocus);
mCounter++;
}
Camera.Parameters params = mCamera.getParameters();
Size size = params.getPreviewSize();
(Some long custom stuff here...)
};