Theres a glitch with my sounds that makes them randomly stop completely if too many are played at once, and then they will start playing again like 20 seconds later. any ideas? heres the code:
Code:
if (mp != null) {
mp.release();
}
// play sound
mp = MediaPlayer.create(this,resId);
if(soundswitch==0) mp.start();
Related
Hey guys I'm building a metronome and am using the MediaPlayer.
Code:
MediaPlayer mp;
.....
public void run() {
if(playing) {
mp.seekTo(0);
mp.start();
}
else
{
mp = MediaPlayer.create(getBaseContext(), R.raw.cowbell);
mp.start();
playing = true;
}
}
the run method is called in regular intervals. There is a delay between the first and second click then it seems to run smoothly. Even so at higher tempos I feel like it is phasing in and out of time. Also the fastest the sound will play is about every 300ms anything faster and there is no noticeable difference.
Any thoughts?
Thanks,
Jordan
I've managed to smooth things out by using SoundPool instead of mediaplayer as its more suited to this sort of thing and I can assume uses less resources. My metronome is still inconsistent though. Is there a better timing method other than using handler/runnable/postdelayed?
hi,all
I am using AudioRecorder to recorder sound and AudioTrack to play it back immediately, but the sound played is strange and there is too much noise in background, below is the code, anyone knows this ? please help, thanks.
init object:
recBufSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding) * 2;
playBufSize = AudioTrack.getMinBufferSize(frequency,
channelConfiguration, audioEncoding) * 2;
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency,
channelConfiguration, audioEncoding, recBufSize);
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, frequency,
channelConfiguration, audioEncoding, playBufSize,
AudioTrack.MODE_STREAM);
recording/play thread:
byte[] buffer = new byte[recBufSize];
audioRecord.startRecording();//recording
audioTrack.play();//playback
while (isRecording) { // thread loop
//read from mic to buffer
int bufferReadResult = audioRecord.read(buffer, 0, recBufSize);
Log.d(TAG, "read bytes: " + bufferReadResult);
//play sound
audioTrack.write(buffer, 0, bufferReadResult);
}
Please use code tags:
type this:
[code]
int main(int argc,char *argv[]){
return 0;
}
[/code]
to get a nicely formated code block like this:
Code:
int main(int argc,char *argv[]){
return 0;
}
Much easier to read.
What is "strange" about the audio? Are you using the phone microphone? If so, I'd expect a lot of noise and low sound quality.
I am making an app that plays sounds in a loop based on a timer. after I exit the program using finish(); the sounds keep playing in background anyway. Any ideas of why this is and how I can fix it (besides having to use a task killer every time)
thanks
hyperbyteX said:
I am making an app that plays sounds in a loop based on a timer. after I exit the program using finish(); the sounds keep playing in background anyway. Any ideas of why this is and how I can fix it (besides having to use a task killer every time)
thanks
Click to expand...
Click to collapse
finish() just closes the activity, it does *NOT* close the app. Threads will continue to run, services will continue to run, broadcast receivers will continue to receive, etc...
You need to actually stop/cancel the timer if you want it to stop.
I recommend reading this (and then re-reading it again): http://developer.android.com/guide/topics/fundamentals.html and this http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html
hyperbyteX said:
I am making an app that plays sounds in a loop based on a timer. after I exit the program using finish(); the sounds keep playing in background anyway. Any ideas of why this is and how I can fix it (besides having to use a task killer every time)
thanks
Click to expand...
Click to collapse
The timer probably uses the system timer service, Which calls your sound file again and again.
Stop the timer in the onDestory function of your activity.
how exactly do I stop it?
hyperbyteX said:
how exactly do I stop it?
Click to expand...
Click to collapse
Take a look at the documentation from google. probably something like .stop(timer)
don't know
heres the code Im using:
// set timer
TimerTask scanTask = null;
final Handler handler = new Handler();
Timer t = new Timer();
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
// stuff to run goes here
}
}
});
}};
t.schedule(scanTask, 1, 50); // time how often stuff happens
I've tried many ways to kill it but nothing seems to work
hyperbyteX said:
heres the code Im using:
// set timer
TimerTask scanTask = null;
final Handler handler = new Handler();
Timer t = new Timer();
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
// stuff to run goes here
}
}
});
}};
t.schedule(scanTask, 1, 50); // time how often stuff happens
I've tried many ways to kill it but nothing seems to work
Click to expand...
Click to collapse
Did you try TimerTask .cancel(); ?
Dark3n said:
Did you try TimerTask .cancel(); ?
Click to expand...
Click to collapse
yeah I tried that but it gives me an error saying "Cannot make a static reference to the non-static method cancel() from the type TimerTask"
Ok, thank you very much. I had to tweak it a bit but I got it!
In my Android app, I have a sound that I want to play when a certain selection has been made from a spinner, but I want it to play the when the user actually makes the proper selection (or just after). My problem is that although the sound does play when they make the correct selection, as long as that selection stays chosen, it also plays every time the app starts up, when it should ONLY play at the time it's chosen. I think I need to change my setOnItemSelectedListener to setOnItemClickListener, but I'm not sure how (still pretty new to java). Can any generous soul out there show me how to change this up (assuming that's how to best solve this problem)?
Here is the code I have now:
Code:
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(
this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.bowchica);
mp.start();
} if(position == 4) {
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.debbie2);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
I haven't try the below code but you can try it on your own and tell us.
In onCreate() declare MediaPlayer mp;
In every if statement that you use for check insert this code:
Code:
if(mp!=null){mp.release();}
int resid = R.raw.yoursound;
mp = MediaPlayer.create(this, resid);
After that override the methods onPause() and onResume() and insert this:
if(mp!=null){mp.release();}
If it is still playing a sound when you start your app, then you should check your code again if you have set as default option any of your selection options.
I would LOVE to try this out...Unfortunately, I'm way too dumb at this point point ot figure out exactly where those code snippets would go inside of what I already have.
Does anyone have a couple of minutes to show me where it would go?
Below is a sample code. Since i don't know your code I give you a snippet that you should adjust it to your code.
Code:
public class SampleSound extends Activity{
private Spinner fitnessSpinner;
private MediaPlayer mp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//here goes your layout
setViews();//here you will set all your views(spinners buttons textviews etc..)
setAdapters();//set your adapters here
setListeners();//
}
private void setListeners() {
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
if(mp!=null){mp.release();}
int resid = R.raw.bowchica;
mp = MediaPlayer.create(this, resid);
mp.start();
} if(position == 4) {
if(mp!=null){mp.release();}
int resid = R.raw.debbie2;
mp = MediaPlayer.create(this, resid);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void setAdapters() {
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
}
private void setViews() {
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
}
public void onResume(){
super.onResume();
if(mp!=null){mp.release();}
}
public void onPause(){
super.onPause();
if(mp!=null){mp.release();}
}
}
I really appreciate the help. I put the code in my routine, but it still plays the sound every time the activity is loaded (as long as the selection in the spinner is correct). It should only play the sound when the correct selection is made.
Any other ideas?
I am sure that your Spinner is set to some value (since you have values to display). Because your Spinner points to a selection (doesn't matter if you have selected or it is selected by default) your sound plays (even when you start the app).
A way to stop the sound playing at start is to declare and an other Item like you did with the previous 4 and set it as default selection of your Spinner.
To sum up:
1.You have to append in R.array.fitness_array an Item (like you did with the previous Items) and give it a name.
2.At the end of method setAdapters() insert this:
Code:
fitnessSpiner.setSelection(5);// or whatever is your selection number
Now it should work but you should know that this is not a good practice and you should try make a ListView or something else.
I'd be happy to change this out to a listview, or whatever would work. I just have to give my user a choice of 4 or 5 items, from which they can choose only one. Something like a drop down box, but in Android, I thought my only option was a spinner. But whatever I use, I have to be able to play a sound when certain items are chosen, but ONLY when those items are chosen, NOT whenever the activity is called up.
Any specific ideas of what I might change to?
What if I had another control like a textview or an edittext (with it's visibility property set to false) that I programatically populated with the users selection (when it's the selection that I want) and then have an OnItemClcickListener set to play the sound?
Could that work?
I will answer from the last to the top of your questions.
1.You can do whatever you want with android. You want TextViews and EditTexts with complex and nested Layouts you can do it. Write services that will communicate with your contacts through a content provider? You can do it.
Write, read and test code. Only this way you will actually learn.
2.Read developer.android.com. Read the android tutorials from there and specifically the Notepad example. You will learn a lot.
A good resource with small examples for ListViews is this.
3.Have you tried the changes I told you from the last post? Did it worked?
Since you just started with android and programming you must first be happy if you have the expected result and then read more to make your code better
Your suggested changes (fitnessSpiner.setSelection(5);// or whatever is your selection number) would stop the sound from playing, but defeat the apps purpose. Every time this activity is loaded, the spinners hit preferences to load the previously stored data. So if I force the spinner to a different selection to NOT play sound when the activity loads, then I would be displaying the wrong data for the user.
Yes you are right. So it is better to make a ListActivity. Read developer.android.com and the link i gave you before. You will be ok with this!
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Lakers16 said:
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Click to expand...
Click to collapse
onClickListener doesn't work for the spinner...I wish it did.
I REALLY need the drop down functionality of teh spinner, so I guess I'm going to try and figure out a way to have an invisible edittext that I set to the spinner selection and then use onClickListener or onChange...
Just started using the Camera2 framework because of the increased control it provides over the low-level functions of the camera. However, I am having some trouble turning the flashlight on and off quickly. With the old Camera API, I could toggle flash while supplying a preview by:
Code:
try
{
android.hardware.Camera.Parameters parameters = c.getParameters();
if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_OFF))
{
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
Log.i("HeartBeatAlgorithm", "LightOn");
}
else if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH))
{
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
Log.i("HeartBeatAlgorithm", "LightOff");
}
c.setParameters(parameters);
}
catch (Exception exception)
{
c.release();
c = null;
}
And the flashlight would quickly turn on or off, without any noticeable interrupt. With Camera2, however, it seems as though flash mode is a property of the CaptureSession, meaning an entirely new CaptureSession needs to be created to change flash mode, i.e.:
Code:
try
{
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
Surface surface = new Surface(texture);
mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
if (mLightNowOn == true)
{
mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
}
else
{
mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
}
mPreviewRequestBuilder.addTarget(surface);
mPreviewRequest = mPreviewRequestBuilder.build();
mCameraDevice.createCaptureSession(Arrays.asList(surface), mSessionStateCallback, null);
}
catch (CameraAccessException e)
{
e.printStackTrace();
}
As is mentioned in the developer docs, "Creating a session is an expensive operation and can take several hundred milliseconds, since it requires configuring the camera device's internal pipelines and allocating memory buffers for sending images to the desired targets." It definitely does, and there is a noticeable delay in my app when toggling flash mode.
I really need to be able to quickly toggle flash modes without interrupting the preview so much. Is there any way around this, or is it unavoidable due to the new API pipeline?