i'm using the Vitamio bundle with success for streaming audio, but in some cases i have to play local audio. Inside MediaPlayerDemo_Audio activity the code says that in that case exists a bug if you want to play audio:
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide its resid in
* MediaPlayer.create() method.
*/
//Bug need fixed
mMediaPlayer = createMediaPlayer(this, R.raw.test_cbr);
mMediaPlayer.start();
}
public MediaPlayer createMediaPlayer(Context context, int resid) {
try {
AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
MediaPlayer mp = new MediaPlayer(context);
mp.setDataSource(afd.getFileDescriptor());
afd.close();
mp.prepare();
return mp;
} catch (IOException ex) {
Log.d(TAG, "create failed:", ex);
// fall through
} catch (IllegalArgumentException ex) {
Log.d(TAG, "create failed:", ex);
// fall through
} catch (SecurityException ex) {
Log.d(TAG, "create failed:", ex);
// fall through
}
return null;
}
The createMediaPlayer method crash when execute mMediaplayer.prepare() method and neither exists the Mediaplayer.create() method, so... What should i do? Thx in advance
Try adding this permission in the manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Related
I'm attempting to create a simple app that records audio. I'm using the standard MediaRecorder to achieve that. Here is what I have so far:
I'm successfully starting the mediaRecorder using this method
public void startRecording(String filePath) throws IOException {
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state + ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(filePath).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC );
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(filePath);
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
} catch (Exception e) {
Timber.e("Error while prepareing media recorder " + e.getMessage());
}
try {
recorder.start();
SharedPrefs.setIsRecording(true);
Timber.d("Started to record " + SharedPrefs.isRecording());
} catch (Exception e) {
Timber.e("Error while starting the media recorder " + e.getMessage());
} }
this works fine and I can see locally that the file is created in the specified folder.
Now this is what I use to stop recording:
public void stopRecording() {
if (recorder == null) {
Timber.e("recorder is null");
}
if (SharedPrefs.isRecording()) {
try {
recorder.stop();
} catch (Exception r) {
Timber.e("Error while attempting to stop " + r.getMessage());
}
try {
recorder.release();
} catch (Exception e) {
Timber.e("Error while attempting to release " + e.getMessage());
}
Timber.e("We stopped recording");
SharedPrefs.setIsRecording(false);
} else {
Timber.e("Attempting to stop recording while not recording ");
} }
Now when stopRecording() is being called this is the error message that I get:
E/MediaRecorder: stop called in an invalid state:1
AudioRecorder: Error while attempting to stop null
Note: When I locally go to the folder where the file is and I refresh it, I can see the size of the file is incrementing.
Thanks in advance!
I need the method that my app run multiple mp3s. Each mp3 must play after previous mp3.
I created method that play sound
void PlaySentence(String path){
try {
AssetFileDescriptor afd = getAssets().openFd(path);
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
player.start();
}
catch (Exception ex)
{
if (BuildConfig.DEBUG)
Log.d(TAGName, ex.getMessage());
}
}
Then I call that function in OnCreate. I used while loop for playing all mp3 files. But sound mixed to each other. If I use loops and isPlaying method the application didn't respond.
while (currentMp3<totalMp3) {
if (!player.isPlaying()) {
PlaySentence();
}
}
Also I use below method for avoid of mixing sounds. It work for one mp3
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
PlaySentence();
}
});
What is the best solution to do that?
You should use setOnCompletionListener, but declare your player as a class member, initalize it in onCreate, and don't create a new one for each mp3. PlaySentence should be something as:
void PlaySentence(String path){
try {
AssetFileDescriptor afd = getAssets().openFd(path);
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
player.start();
}
catch (Exception ex)
{
if (BuildConfig.DEBUG)
Log.d(TAGName, ex.getMessage());
}
}
I am using MediaPlayer to playback audio file of .WAV format. When I debug the app I'm able to play file but when I run the app file is not playing.
There is a similar issue regarding this but no solution is provided.
Below is the code which i am using
MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(mContext, fileUri);// uri of the audio file
mMediaPlayer.prepare();
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.start();// to start the playback of the audio file
This code is working only in debug mode but not in normal mode.
Thanks
This is what I am saying:
btn_next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.reset();
mp.setDataSource(url.toString());
mp.setOnErrorListener(this);
mp.setOnPreparedListener(this);
mp.setOnCompletionListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
Log.e(TAG, "SecurityException");
} catch (IllegalStateException e) {
Log.e(TAG, "IllegalStateException");
} catch (IOException e) {
Log.e(TAG, "IOException");
}
mp.prepareAsync();
}
});
Now, override method onPrepared().
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
}
Comment below if you face any issue in this.
I have 10 buttons for playing 10 songs. i want to achieve when i press the same button while playing, it should be stop . when i press the another button it should be stop the previous song and play the new song ..
but i couldn't achieve both things using same code
i have tried it
when i use this code ,the stop won't work for same button, but it worked for another playing new song .
private void playSample(int[] res, int position)
{
AssetFileDescriptor afd = getApplicationContext().getResources().openRawResourceFd(res[position]);
try
{ if(mp.isPlaying())
{
mp.stop();
}
mp.reset();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mp.prepare();
mp.start();
afd.close();
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IllegalStateException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IOException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
}
so i have tried like this
private void playSample(int[] res, int position)
{
AssetFileDescriptor afd = getApplicationContext().getResources().openRawResourceFd(res[position]);
try
{ if(mp.isPlaying())
{
mp.stop();
}else
mp.reset();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mp.prepare();
mp.start();
afd.close();
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IllegalStateException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IOException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
}
now the stop will work for same button .but when i press another button while playing .it wont start the new song
check if media playing just stop it and play requested media.no need to else.
if(mp.isPlaying())
mp.stop();
mp.reset();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mp.prepare();
mp.start();
afd.close();
I guess the problem is calling start without waiting for onPrepared listener. Error (-38,0) is invalid operation, so which mostly probably be calling start when it was not even finished preparing.
private void openVideo() {
if (mUri == null || mSurfaceHolder == null) {
// not ready for playback just yet, will try again later
return;
}
// Tell the music playback service to pause
// TODO: these constants need to be published somewhere in the framework.
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
mContext.sendBroadcast(i);
if (mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnPreparedListener(mPreparedListener);
mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
mIsPrepared = false;
Log.v(TAG, "reset duration to -1 in openVideo");
mDuration = -1;
mMediaPlayer.setOnCompletionListener(mCompletionListener);
mMediaPlayer.setOnErrorListener(mErrorListener);
mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
mCurrentBufferPercentage = 0;
mMediaPlayer.setDataSource(mContext, mUri);
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.prepareAsync();
attachMediaController();
} catch (IOException ex) {
Log.w(TAG, "Unable to open content: " + mUri, ex);
return;
} catch (IllegalArgumentException ex) {
Log.w(TAG, "Unable to open content: " + mUri, ex);
return;
}
}
I got this code from GrepCode (VideoView).I would like to add Mute and unmute functions on my videoview hence am trying to create a new videoview.But due to this mContext variable i am not able to set the path for my mediaplayer.
Purpose of Mute and Unmute: To play other audios with the same audio..
I want to access the Mediaplayer for mute and unmute function and hence am not overriding my videoview class.
Am a newbie to android so suggest me some methods to achieve this. Thanks in advance.