how to develop a custom equilizer for media player in android? - android

I am developing app related to music player, its having equalizer settings, i know every device having a default equalizer. code for getting the default equalizer
equilizer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL);
i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, mp.getAudioSessionId());
startActivityForResult(i, 11113);
}
});
}
In onActivityResult:
protected void onActivityResult(int requestCode,int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
return;
}
}
Using the above code we can get default equalizer, but my requirement is design a equalizer with different UI and add some more effects to the equalizer.
Can any one give me an idea how can I do that?

There is an Equalizer effect. You can pass the audio session ID of the MediaPlayer to its constructor:
// Given a MediaPlayer mp
Equalizer eq = new Equalizer(0, mp.getAudioSessionId());
Here is an example program that uses it. I haven't built it to see, but it at least hooks up the equalizer correctly.

Related

How to stop media player from another activity in Android programmatically?

I am trying to use media player in my app and I have trying to stop media player from other activity my coding is following:
FirstActivity:
public void stop() {
if (playPause == false) {
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
new Player().cancel(true);
media.stop();
media.reset();
mediaPlayer.reset();
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
media.stop();
playPause = true;
} else {
control.setBackgroundResource(R.drawable.pause);
if (intialStage) {
new Player()
.execute(URL);
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = false;
}
}
SecondActivity:
Have to stop media player after the timer is end:
#Override
public void onFinish() {
textViewTime.setText(hmsTimeFormatter(timeCountInMilliSeconds));
// call to initialize the progress bar values
setProgressBarValues();
// hiding the reset icon
imageViewReset.setVisibility(View.GONE);
// changing stop icon to start icon
imageViewStartStop.setImageResource(R.drawable.icon_start);
// making edit text editable
editTextMinute.setEnabled(true);
// changing the timer status to stopped
timerStatus = TimerStatus.STOPPED;
MainActivity main = new MainActivity();
main.stop();
}
}.start();
countDownTimer.start();
}
the above coding is shows error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setBackgroundResource(int)' on a null object reference
at com.digitamatix.mukilfm.MainActivity.stop(MainActivity.java:549)
I have to stop media player in first activity please help me on my coding to fix my issues
see i have started activity with startActivityForResult . onActivityResult you will get result.
startActivityForResult(Activity1.createIntent(this), 1001);
//handle callback result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1001) {
}
}
}
Below code will call in next activity where you want to callback and finish the activity. You can pass any value with this intent.
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
So, as per requirement you can use this. Stop media player. Other option local broadcast too.
Hope this will help you.
(Based on the code you posted)
Looks like the problem here is that you are calling a method which refers to an xml resource from an activity which is not visible.
You are creating an istance of the MainActivity but, since it's never been shown, the onCreate and other lifecycle methods are never fired and your control is null.
You have at least 3 ways for doing it:
Create a method which doesn't refer to any xml resource, and it just stop the player
1B. Try using setResult, it's not a good practice to reference a new istance of a running activity. Just use StartActivityForResult(activityB) and setResult(res) for firing the onActivityResult callback.
Put the player in a Singleton and refer to it wherever you are
Use fragment navigation instead of activity and refer to the player in main activity
Hope this helps!

Text to Speech Crashes

I've got a problem with android TTS.
I've built a game which announces a number for every cycle of game play. After a number of cycles the game crashes. Looking at the logcat it appear that the AudioPlayer is running out of room "AudioFlinger? no more track names available".
So after a little searching I've found this question.
AudioFlinger could not create track. status: -12
Which helpfully points out that Android has a hard limit of 32 active AudioTrack objects per device. Checking back to the logcat I found that it had announced 32 times. So seems that I am running out of objects.
So my initial idea was to shut down the TTS engine and re-initialise it after 30 announcements, there would be a short pause it game play but not too bad. This unfortunately didn’t do the trick. It seems that shutting down the TTS engine doesn’t reset the AudioTrack objects.
I've played around with the game and found that you can play up to before the crash, close the program, restart it and keep on playing with no crashes (until it reaches 32 continuous plays.) So there is a way to release the AudioTrack objects, in the logcat it talks about “AwesomePlayer reset” searching online I don't think there's is a way to control the AwesomePlayer.
So my question is, how do I clear the AudioTrack objects? There is a function “release()” and There is only one set of AudioTracks, I'm just not sure on how to get that to work.
Any other ideas on how to clear the AudoTrack objects would be welcome.
Thank TC
P.S. I'm pretty sure I've implemented the TTS correctly here's my code
private void playNumber() {
if (inPlay) {
numbersPlayed += 1;
Log.d("TOM", "playNumber");
Locale loc = new Locale("spa", "ESP");
mTts.setLanguage(loc);
String genNum = String.valueOf(generatedNumber);
Log.d("TOM", "genNum to String");
HashMap<String, String> map = new HashMap<String, String>();
Log.d("TOM", "toHashMap");
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "TTS Stopped");
Log.d("TOM", "mapPut");
mTts.speak(genNum, TextToSpeech.QUEUE_FLUSH, map);
Log.d("TOM", "TTSSpeak");
mTts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
enterLock = true;
Log.d("TOM", "uttStart");
}
#Override
public void onDone(String utteranceId) {
enterLock = false;
timerCount.start();
Log.d("TOM", "uttDone");
}
#Override
public void onError(String utteranceId) {
Log.d("TOM", "uttError");
}
});
}
}
public void onInit(int i) {
if (generatedNumber == -2) {
enterLock = false;
Toast.makeText(this, getString(R.string.ttsReady_toast), Toast.LENGTH_SHORT).show();
Log.d("TOM", "onInit: " + Boolean.toString(inPlay));
} else {
playNumber();
Log.d("TOM", "New Start Play");
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
mTts = new TextToSpeech(this, this);
Log.d("TOM", "ttsEngineOK");
} else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
Log.d("TOM", "ttsEngineError");
}
}
}
I figured out my problem.
I feel a bit silly really, the problem had nothing to do with the TTS engine. The actual problem lied in the mediaplayer clip that I was playing when the player got a correct answer. The way I had it set up, every time the answer was correct a new mediaplayer object was created and so this hit the 32 AudioTrack limit not the TTS. I've just put the mediaPlayer.create function in onCreate where it should have been and everything is fine now!!!
That teaches me for not putting all my code on, I'm sure someone with more experience would have noticed that straight away.

Stream and Play .m4a stream (Itunes preview Url) in android

I want to stream and play itunes preview urls like http://a2.mzstatic.com/us/r1000/044/Music/e9/40/ec/mzm.evyxvimp.aac.p.m4a. I tried to use AAC Decoder Android Library. By which I can stream and play AAC stream urls like http://http.yourmuze.com:8000/play/paradise/l.aac. But it dnt stream m4a urls(Logcat says java.io.FileNotFoundException: http://a2.mzstatic.com/us/r1000/044/Music/e9/40/ec/mzm.evyxvimp.aac.p.m4a).
How I can stream the .m4a links?
My Code:
public class AACPlayerActivity extends Activity implements OnClickListener,PlayerCallback{
private Button btnPlay;
private ProgressBar progress;
private Handler uiHandler;
private MultiPlayer multiPlayer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnPlay = (Button)findViewById(R.id.playButton);
progress = (ProgressBar)findViewById(R.id.progress);
progress.setVisibility(View.INVISIBLE);
btnPlay.setOnClickListener(this);
uiHandler = new Handler();
}
public void playerException(Throwable arg0) {
// TODO Auto-generated method stub
}
public void playerMetadata(String arg0, String arg1) {
// TODO Auto-generated method stub
}
public void playerPCMFeedBuffer(boolean arg0, final int audioBufferSizeMs, final int audioBufferCapacityMs) {
// TODO Auto-generated method stub
uiHandler.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
progress.setProgress( audioBufferSizeMs * progress.getMax() / audioBufferCapacityMs );
}
});
}
public void playerStarted() {
uiHandler.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
progress.setProgress( 0 );
progress.setVisibility( View.VISIBLE );
}
});
}
public void playerStopped(int arg0) {
// TODO Auto-generated method stub
uiHandler.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
progress.setVisibility( View.INVISIBLE );
}
});
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(btnPlay.getText().equals("Play")){
start();
btnPlay.setText("stop");
}else{
stop();
}
}
private void start() {
stop();
// we cannot do it in playerStarted() - it is too late:
multiPlayer = new MultiPlayer(this,MultiPlayer.DEFAULT_AUDIO_BUFFER_CAPACITY_MS, MultiPlayer.DEFAULT_DECODE_BUFFER_CAPACITY_MS);
multiPlayer.playAsync("http://a2.mzstatic.com/us/r1000/044/Music/e9/40/ec/mzm.evyxvimp.aac.p.m4a");
}
private void stop() {
if (multiPlayer != null) {
multiPlayer.stop();
multiPlayer = null;
}
}
Updates
I try to use ServeStream it says the url could not be opened.
I try to use Vitamio SDK it also fails to play the itunes preview Urls.
Is possible to play itunes preview urls in android?
Take a look at ServeStream:
HTTP media server browser and stream player for Android.
Features:
Supports Android 2.2+, 3.0+ (No support for < 2.2)
Plays Android supported media files
Additional support for m3u, m3u8, pls and asx playlists
Supports multitasking/playing audio in the background
Repeat and shuffle modes
Alarm clock support
Home screen widget
Utilizes HTML parsing to allow navigation of HTTP media servers that serve HTML pages
M4A and AAC are supported by Android. I would recommend to read this page: http://developer.android.com/guide/appendix/media-formats.html
Just couple of thing which you should be aware of
a) Older devices may have no particular coded or format support (especially, if you go below OS 2.2)
b) Some cheap devices may have quite strange things integrated in audio/video stack. I saw it on couple of cheap Chinese devices.
So, you can try to use MediaPlayer API to play it:
http://developer.android.com/reference/android/media/MediaPlayer.html
You can take a look at example here:
http://blog.endpoint.com/2011/03/api-gaps-android-mediaplayer-example.html
It has nothing to do with media formats etc. Apple simply prevents non-Apple clients to access previews. You can spoof User-Agent header and access to previews.
Read my relevant blog post here: http://ahmetalpbalkan.com/blog/how-to-bypass-itunes-music-previews-protection/ Thats why you get 404 while playing music on Android. this should answer your question.

How to use the microphone on Android

I have just started to develop my first Android app, and I am having a hard time figuring out how to start the microphone and have it listen, which is a main feature of my app.
I've searched the Android docs and I can't find much info on this.
Thanks in advance.
Maybe this can help (actually from the Android docs):
Audio Capture
Create a new instance of android.media.MediaRecorder.
Set the audio source using MediaRecorder.setAudioSource(). You will probably want to use MediaRecorder.AudioSource.MIC.
Set output file format using MediaRecorder.setOutputFormat().
Set output file name using MediaRecorder.setOutputFile().
Set the audio encoder using MediaRecorder.setAudioEncoder().
Call MediaRecorder.prepare() on the MediaRecorder instance.
To start audio capture, call MediaRecorder.start().
To stop audio capture, call MediaRecorder.stop().
When you are done with the MediaRecorder instance, call MediaRecorder.release() on it. Calling MediaRecorder.release() is always recommended to free the resource immediately.
or:
Android Audio Recording Tutorial
You can use custom recorder:
final static int RQS_RECORDING = 1;
Uri savedUri;
Button buttonRecord;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
buttonRecord = (Button) findViewById(R.id.record);
buttonRecord.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(
MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, RQS_RECORDING);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == RQS_RECORDING) {
savedUri = data.getData();
Toast.makeText(MainActivity.this,
"Saved: " + savedUri.getPath(), Toast.LENGTH_LONG).show();
}
}

How to pause my application's audio/music after launching google's Voice Search (Speech Recognition)?

I made an Audio-Player and I need to pause it when the user launches google Voice Search.
I just tried 2 ways, but all failed
Write an receiver to receive broadcast action intent
"android.speech.action.RECOGNIZE_SPEECH", but it doesn't work at all, can not receive callback from Voice Search.
Write a service to get SpeechRecognizer, as following, (partial of my codes)
code:
public class VoiceSearchMonitor extends Service
{
#Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// Get SpeechRecognizer
SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(context);
// Create a new RecognitionListener
RecognitionListener listener = new RecognitionListener()
{
#Override
public void onReadyForSpeech(Bundle params)
{
// *** I want to pause my audio here ***
}
#Override
public void onEndOfSpeech()
{
// *** I want to resume my audio here ***
}
}
// make an intent
Intent intent = new Intent("android.speech.action.RECOGNIZE_SPEECH");
// Start listening
recognizer.setRecognitionListener(listener);
recognizer.startListening(intent);
}
}
Just can not receive the callback onReadyForSpeech, 'onEndOfSpeech' after I launch Voice Search, so there's no way for me to pause my audio. I just wonder if there is a way to get SpeechRecognizer instance of google's Voice Search, so that I can get the callback correctly??
Does anyone know the answer to my question? Thanks for helping!!!
Joy
I took the same route initially for this issue, but the solution is to use the AudioManager rather than the SpeechRecognizer.
Our app was already using a custom listener for AudioManager.OnAudioFocusChangeListener and was correctly responding to the AUDIOFOCUS_GAIN and AUDIOFOCUS_LOSS states. It turns out that the voice search triggers an AUDIOFOCUS_LOSS_TRANSIENT state, so adding that to the change listener resulted in playback being paused while the voice search was performed.
To summarize:
Create the listener
AudioManager.OnAudioFocusChangeListener audioFocusListener =
new AudioManager.OnAudioFocusChangeListener() {
#Override
public void onAudioFocusChange(int focusChange) {
Logging.d(TAG, "audiofocus change");
if(focusChange == AudioManager.AUDIOFOCUS_LOSS || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
suspendPlayback();
if(focusChange == AudioManager.AUDIOFOCUS_GAIN)
resumePlayback();
}
};
Get the AudioManager, request focus, and pass the listener
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);

Categories

Resources