Example for BeatDetect Minim - android

I am using this code to record the current sound. I need now some processing to detect the beat from music. I want a LED go on/off according the incoming music. I think BeatDetect is an useful library for my project, however I cannot find a good example. Can anyone give me an easy example to use? Or a reference?
public void start() {
initializeMediaRecorder();
handler.postDelayed(new Runnable() {
#Override
public void run() {
notifySample(getAmplitude());
handler.postDelayed(this, 150);
}
}, 150);
}
public void stop() {
handler.removeCallbacksAndMessages(null);
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
mediaRecorder = null;
}
}
private double getAmplitude() {
if (mediaRecorder != null) {
return mediaRecorder.getMaxAmplitude();
} else {
return 0;
}
}
private void initializeMediaRecorder(){
try {
if(mediaRecorder == null) {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile("/dev/null");
mediaRecorder.prepare();
mediaRecorder.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Save video file when the app goes in background [Camera2Api]

I have a camera app. My problem is that when i'm recording and the app goes in bacground the file that mediarecorder had is void. I want to save the file is saved first. I have tried the same code that i use when a click the stop button, but it does not work.
Any suggestions?
This is my onPause() method
#Override
public void onPause() {
if (isRecording) {
stopRecordingVideo();
Log.d("YUI", "true");
fileQueue.addToQueue(mCurrentFile);
} else {
Log.d("YUI", "false");
mMediaRecorder = null;
closeCamera();
}
counter--;
stopBackgroundThread();
// if (mCurrentFile != null) {
// mCurrentFile.delete(); // delete empty file
// }
super.onPause();
}
public void stopRecordingVideo() {
stopRecordingVideo(false);
}
private void stopRecordingVideo(boolean kill) {
// UI
isRecording = false;
// Stop Recording
closeCamera();
if (!kill) {
openCamera(mCameraLayout.getWidth(), mCameraLayout.getHeight());
}
}
private void closeCamera() {
try {
mCameraOpenCloseLock.acquire();
if (mPreviewSession != null) {
mPreviewSession.close();
mPreviewSession = null;
}
if (mCameraDevice != null) {
mCameraDevice.close();
mCameraDevice = null;
}
if (mMediaRecorder != null) {
mMediaRecorder.stop();
mMediaRecorder.release();
mMediaRecorder = null;
}
} catch (InterruptedException ie) {
Crashlytics.log("closeCamera error");
Crashlytics.logException(ie);
ie.printStackTrace();
getCam2Listener().onInterruptedException(ie);
throw new RuntimeException("Interrupted while trying to lock camera closing.");
} catch (Exception exc) {
Crashlytics.log("closeCamera error");
Crashlytics.logException(exc);
}
finally {
mCameraOpenCloseLock.release();
}
}

Xamarin - How to set/change VideoView display preview orientation

I copied a code from here https://developer.xamarin.com/recipes/android/media/video/record_video/, an instruction on making videostream and I am trying to change some part of it.
I already tried to change the output orientation to 90 using SetOrientationHint(90)
But since this code do not use the Camera class and just a MediaRecorder class. How can I rotate the display preview because it is giving me a +90degrees and landscape preview?
I already tried the rotation in xml and code but the preview became a total black.
This is the code
[Activity(Label = "App2", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity, ISurfaceHolderCallback
{
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
MediaRecorder recorder;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
//Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var record = FindViewById<Button>(Resource.Id.Record);
var stop = FindViewById<Button>(Resource.Id.Stop);
var play = FindViewById<Button>(Resource.Id.Play);
var video = FindViewById<VideoView>(Resource.Id.SampleVideoView);
//video.Rotation = 90;
record.Click += delegate
{
if (recorder == null)
recorder = startRecording(video);
else
Toast.MakeText(this, "Now recording", 0).Show();
};
stop.Click += delegate
{
if (recorder != null)
{
stopRecording(recorder);
recorder = null;
}
else
Toast.MakeText(this, "No video recording", 0).Show();
};
play.Click += delegate
{
if (path != null)
playVideo(video);
else
Toast.MakeText(this, "No video available", 0).Show();
};
//recorder = startRecording(video);
}
protected override void OnDestroy()
{
base.OnDestroy();
if (recorder != null)
{
recorder.Release();
recorder.Dispose();
recorder = null;
}
}
private void playVideo(VideoView video)
{
var uri = Android.Net.Uri.Parse(path);
video.SetVideoURI(uri);
video.Start();
}
private static void stopRecording(MediaRecorder recorder)
{
if (recorder != null)
{
recorder.Stop();
recorder.Release();
}
}
private MediaRecorder startRecording(VideoView video)
{
MediaRecorder recorder;
video.StopPlayback();
//video.Holder.AddCallback(this);
//video.Holder.SetType(SurfaceType.PushBuffers);
recorder = new MediaRecorder();
recorder.SetVideoSource(VideoSource.Camera);
recorder.SetAudioSource(AudioSource.Mic);
recorder.SetOutputFormat(OutputFormat.Default);
recorder.SetVideoEncoder(VideoEncoder.Default);
recorder.SetAudioEncoder(AudioEncoder.Default);
recorder.SetOutputFile(path);
recorder.SetOrientationHint(90);
recorder.SetPreviewDisplay(video.Holder.Surface);
if (recorder!=null)
{
try
{
recorder.Prepare();
recorder.Start();
}
catch (Exception)
{
Toast.MakeText(this, "Exception!", 0).Show();
}
}
return recorder;
}
public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
{
throw new NotImplementedException();
}
public void SurfaceCreated(ISurfaceHolder holder)
{
throw new NotImplementedException();
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
throw new NotImplementedException();
}
}
UPDATE
#Elvis Xia's answer helped a lot.
Here is the new code
[Activity(Label = "App2", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity, ISurfaceHolderCallback
{
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
MediaRecorder recorder;
Android.Hardware.Camera mCamera; //Android.Hardware is used because it will have
//problem with Android.Graphics
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
//Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var record = FindViewById<Button>(Resource.Id.Record);
var stop = FindViewById<Button>(Resource.Id.Stop);
var play = FindViewById<Button>(Resource.Id.Play);
var video = FindViewById<VideoView>(Resource.Id.SampleVideoView);
record.Click += delegate
{
if (recorder == null)
recorder = startRecording(video);
else
Toast.MakeText(this, "Now recording", 0).Show();
};
stop.Click += delegate
{
if (recorder != null)
{
stopRecording(recorder, mCamera);
recorder = null;
}
else
Toast.MakeText(this, "No video recording", 0).Show();
};
play.Click += delegate
{
if (path != null)
playVideo(video);
else
Toast.MakeText(this, "No video available", 0).Show();
};
//recorder = startRecording(video);
}
protected override void OnDestroy()
{
base.OnDestroy();
if (recorder != null)
{
recorder.Release();
recorder.Dispose();
recorder = null;
}
}
private void playVideo(VideoView video)
{
var uri = Android.Net.Uri.Parse(path);
video.SetVideoURI(uri);
video.Start();
}
private static void stopRecording(MediaRecorder recorder, Android.Hardware.Camera mCamera)
{
if (recorder != null)
{
recorder.Stop();
recorder.Release();
mCamera.StopPreview();
mCamera.Release();
}
}
private MediaRecorder startRecording(VideoView video)
{
MediaRecorder recorder;
video.StopPlayback();
//video.Holder.AddCallback(this);
//video.Holder.SetType(SurfaceType.PushBuffers);
recorder = new MediaRecorder();
mCamera = GetCameraInstance();
mCamera.SetDisplayOrientation(90);
mCamera.Unlock();
recorder.SetCamera(mCamera);
recorder.SetVideoSource(VideoSource.Camera);
recorder.SetAudioSource(AudioSource.Mic);
recorder.SetOutputFormat(OutputFormat.Default);
recorder.SetVideoEncoder(VideoEncoder.Default);
recorder.SetAudioEncoder(AudioEncoder.Default);
recorder.SetOutputFile(path);
recorder.SetOrientationHint(90);
recorder.SetPreviewDisplay(video.Holder.Surface);
if (recorder!=null)
{
try
{
recorder.Prepare();
recorder.Start();
}
catch (Exception)
{
Toast.MakeText(this, "Exception!", 0).Show();
}
}
return recorder;
}
public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
{
throw new NotImplementedException();
}
public void SurfaceCreated(ISurfaceHolder holder)
{
throw new NotImplementedException();
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
throw new NotImplementedException();
}
public static Android.Hardware.Camera GetCameraInstance()
{
Android.Hardware.Camera c = null;
try
{
c = Android.Hardware.Camera.Open();
}
catch (Exception e)
{
}
return c;
}
}
But since this code do not use the Camera class and just a MediaRecorder class. How can I rotate the display preview because it is giving me a +90degrees and landscape preview?
You need to associate Camera with MediaRecorder after setting the rotation degree:
get an Camera Instacnce through GetCameraInstace:
public static Camera GetCameraInstance()
{
Camera c = null;
try
{
c = Camera.Open();
}
catch (Exception e)
{
}
return c;
}
In MainActivity.cs record button click event, associate the camera with MediaRecorder and set the orientation before mCamera.Unlock:
Camera mCamera
...
recorder = new MediaRecorder();
mCamera = ClassName.GetCameraInstance(); //ClassName if in different class.
//else just GetCameraInstance();
mCamera.SetDisplayOrientation(90);
mCamera.Unlock();
recorder.SetCamera(mCamera);
recorder.SetVideoSource(VideoSource.Camera);

Video Recording using GLSurfaceview in android

I'm trying to record video by using GLSurfaceview in android. But every time when i tap to record, it gives me null pointer exception onPause.
here is my code to record video
mCamera = new CameraLoader();
buttonn_capture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try{
if (recording) {
mediaRecorder.stop(); // stop the recording
recording = false;
} else {
// Release Camera before MediaRecorder start
mCamera.releaseCamera();
if (!prepareMediaRecorder()) {
finish();
}
try {
mediaRecorder.prepare();
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaRecorder.start();
recording = true;
// myButton.setText("Cancel");
}
}catch(Exception ex){
Toast.makeText(getApplicationContext(), "Please tap and hold to record!",
Toast.LENGTH_LONG).show();
reload();
}
}
});
private boolean prepareMediaRecorder() {
mCamera.mCameraInstance.unlock();
mediaRecorder.setCamera(mCamera.mCameraInstance);
// Step 2: Set sources
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),
"MusicDubs");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
.format(new Date());
CameraInfo caminfo = new CameraInfo();
mCamera.mCameraInstance.getCameraInfo(0, caminfo);
if (caminfo.facing == CameraInfo.CAMERA_FACING_FRONT) {
mediaRecorder.setProfile(CamcorderProfile.get(0,
CamcorderProfile.QUALITY_HIGH));
mediaRecorder
.setOrientationHint(270);
} else if (caminfo.facing == CameraInfo.CAMERA_FACING_BACK) {
mediaRecorder.setProfile(CamcorderProfile.get(0,
CamcorderProfile.QUALITY_HIGH));
mediaRecorder
.setOrientationHint(270);
mediaRecorder.setOrientationHint(90);
}
//mediaRecorder.setCaptureRate(20);
mediaRecorder.setVideoFrameRate(120);
mediaRecorder.setOutputFile(mediaStorageDir.getPath() + "/"
+ "_" + timeStamp + ".mp4");
// Step 5: Set the preview output
mediaRecorder.setPreviewDisplay(glSurfaceView.getHolder()
.getSurface());
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
// releaseMediaPlayer();
return false;
} catch (IOException e) {
releaseMediaRecorder();
// releaseMediaPlayer();
return false;
}
return true;
}
private void releaseMediaRecorder() {
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
mCamera.mCameraInstance.lock(); // lock camera for later use
}
}
on Activity pause and resume i added that code
#Override
protected void onResume() {
super.onResume();
mCamera.onResume();
}
#Override
protected void onPause() {
mCamera.onPause();
super.onPause();
}
here is my camera class to load camera
private class CameraLoader {
private int mCurrentCameraId = 0;
private Camera mCameraInstance;
public void onResume() {
setUpCamera(mCurrentCameraId);
}
public void onPause() {
releaseCamera();
}
public void switchCamera() {
releaseCamera();
mCurrentCameraId = (mCurrentCameraId + 1) % mCameraHelper.getNumberOfCameras();
setUpCamera(mCurrentCameraId);
}
private void setUpCamera(final int id) {
mCameraInstance = getCameraInstance(id);
Parameters parameters = mCameraInstance.getParameters();
// TODO adjust by getting supportedPreviewSizes and then choosing
// the best one for screen size (best fill screen)
if (parameters.getSupportedFocusModes().contains(
Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
mCameraInstance.setParameters(parameters);
int orientation = mCameraHelper.getCameraDisplayOrientation(
ActivityCamera.this, mCurrentCameraId);
CameraInfo2 cameraInfo = new CameraInfo2();
mCameraHelper.getCameraInfo(mCurrentCameraId, cameraInfo);
boolean flipHorizontal = cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT;
mGPUImage.setUpCamera(mCameraInstance, orientation, flipHorizontal, false);
}
/** A safe way to get an instance of the Camera object. */
private Camera getCameraInstance(final int id) {
Camera c = null;
try {
c = mCameraHelper.openCamera(id);
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
private void releaseCamera() {
mCameraInstance.setPreviewCallback(null);
mCameraInstance.release();
mCameraInstance = null;
}
}
Its behavior is very strange, I didn't get why it is giving me null pointer exception onPause because there is no point of getting camera null there. please tell me where i'm doing wrong. Any help would be much appreciated. Thank you :)

How to record a part of voice when it playing

I have a hard issue about audio recording in android. I used AudioTrack to play my sound when I speak to my phone. I want to record a part in my voice if i press button record. For example, I will speak within 10 seconds. However, I only want to record my sound iff I press record button. It can be from 3th second to 8th second. However, my phone need to play my sound during I speaking (from 1st to 10th second).
Currently, I used a thread to play my sound as following code. I created a flag in the recording thread to decide when I will record. When I press button record, the flag will be set true. And I click stop, It will set false and write to file
public class AudioSoundThread extends Thread {
private short[] audioBuffer;
private boolean isRecording = false;
private boolean isSounding = true;
private AudioRecordingHandler handler = null;
private AudioRecord record;
private AudioTrack track;
public AudioSoundThread(AudioTrack mtrack,AudioRecord mrecord,short[] maudioBuffer, AudioRecordingHandler handler) {
this.handler = handler;
this.audioBuffer = maudioBuffer;
this.record=mrecord;
this.track=mtrack;
}
#Override
public void run() {
record.startRecording();
DataOutputStream output =null;
if(isRecording){
output = prepareWriting();
if (output == null) { return; }
}
track.play();
///////////Play during recording
int readSize =0;
while (isSound) {
readSize=record.read(audioBuffer, 0, audioBuffer.length);
if ((readSize == AudioRecord.ERROR_INVALID_OPERATION) ||
(readSize == AudioRecord.ERROR_BAD_VALUE) ||
(readSize <= 0)) {
continue;
}
if(AudioRecord.ERROR_INVALID_OPERATION != readSize){
track.write(audioBuffer, 0, readSize);
}
if(isRecording)
write(output,readSize);
//Finished to write
if(!isRecording&&output!=null)
{
finishWriting(output);
File waveFile = getFile("wav");
try {
rawToWave(mRecording, waveFile);
deleteTempFile(mRecording);
} catch (IOException e) {
Log.e("Error writing file : ", e.getMessage());
}
}
}
record.stop();
record.release();
}
public synchronized void stopSound() {
isSound = false;
}
public synchronized void startSound() {
isSound = true;
}
public synchronized void startRecordingFlag() {
isRecording = true;
}
public synchronized void stopRecording() {
isRecording = false;
}
private void finishWriting(DataOutputStream out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
if (handler != null) {
handler.onRecordingError();
}
}
}
private DataOutputStream prepareWriting() {
if (mRecording.exists()) { mRecording.delete(); }
DataOutputStream out = null;
try {
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(mRecording)));
} catch (FileNotFoundException e) {
e.printStackTrace();
if (handler != null) {
handler.onRecordingError();
}
}
return out;
}
In mainActivity, I have two buttons that are play my sound and button recording
private AudioSoundThread recordingThread;
//Play button
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startSounding();
}
});
//Record button
btnRecord = (Button) findViewById(R.id.btnRecord);
btnRecord.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//record();
recordingThread.startRecordingFlag();
}
});
//Stop Record button
btnStopRecord = (Button) findViewById(R.id.btnStopRecord);
btnStopRecord .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//record();
recordingThread.stopRecording();
}
});
private void startSounding() {
soundingThread = new AudioSoundThread(track,mRecorder,mBuffer,new AudioRecordingHandler() {
});
soundingThread.start();
}
However, my scheme does not work. I think that my flag cannot send to the thread. Could you look at my code and give me one solution?

Android game wont start (restart) after hitting back key

i'm having a problem with restarting my game after clicking home or return button on android.
I've found partial solution in thread:
Android crash when app is closed and reopened, but the game after restarting dosen't work properly.
It only shows images/sprites which also moves, but dosen't read touches.
//this is in game view
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) { // ce se spremeni zaslon
}
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
start();
}
public void start() {
loop.setRunning(true);
if (!mGameIsRunning) {
loop.start();
mGameIsRunning = true;
} else {
loop.onResume();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (retry) {
try {
loop.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
//and this is game thread
while (running) {
canvas = null;
try{
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
beginTime = System.currentTimeMillis();
framesSkipped = 0;
this.gameView.update();
this.gameView.render(canvas);
synchronized (mPauseLock) {
while (mPaused) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
}
}
}
timeDiff = System.currentTimeMillis() - beginTime;
sleepTime = (int)(FRAME_PERIOD - timeDiff);
if (sleepTime > 0){
try{
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
}
} finally {
if (canvas != null){
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
public void onPause() {
synchronized (mPauseLock) {
mPaused = true;
}
}
public void onResume() {
synchronized (mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();
}
}
Can anyone tell me if there is any mistake or any other solution.
Thanks for help.
Or if anyone could tell me for a good way to stop game and restart it, please?
I fixed it so that it works when i hit home, but when i hit back and restart it, I get black screen.
// current gameview code
public void surfaceCreated(SurfaceHolder holder) {
if (loop==null)
loop = new GameLoop(getHolder(), this);
if(loop.getState() == Thread.State.TERMINATED)
{
loop = new GameLoop(getHolder(), this);
}
start();
}
public void start() {
if (!mGameIsRunning) {
mGameIsRunning = true;
loop.setRunning(true);
loop.start();
} else {
loop.onResume();
loop.start();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
loop.onPause();
}
I have a feeling that the problem is in surfaceDestroy method, but I'm not sure since I don't know what is the difference between hitting home or back key.

Categories

Resources