how to play a different sound in a string selection? - android

first of all, I'm starting yesterday on Android programming. I'm making a String, and in each selection I wanna play diferent sound. Ok, i've got the one, but in the other selection play the same sound because I don't know how to do it; maybe a Switch with different cases? thanks
now I have this code.`
import android.app.ListActivity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class sonidos extends ListActivity {
public String[] frases = {
"cake",
"butter",
"apple",
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, frases));
}
public void onListItemClick(ListView parent, View v){
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.sonidos);
}
public void onListItemClick(ListView parent, View v, long id){
MediaPlayer sound = MediaPlayer.create(sonidos.this, R.raw.dtrain);
if (sound.isPlaying()) {
sound.stop();
} else {
try {
sound.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
}

If you use sound from assets folder you could use something like this:
public void onListItemClick(ListView parent, View v, long id){
MediaPlayer player = new MediaPlayer();
AssetFileDescriptor afd;
try {
switch(id)
{
case 1: afd = getAssets().openFd("cake.mp3"); break;
case 2: afd = getAssets().openFd("butter.mp3"); break;
default : afd = getAssets().openFd("apple.mp3"); break;
};
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
} catch (IOException e) {
e.printStackTrace();
SM.Exception("## Exception playing sound!");
}
if (player.isPlaying()) {
player.stop();
}
else {
try {
player.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
Hope this helps.

You need to write something like this:
public void onListItemClick(ListView parent, View v, long id){
MediaPlayer sound = null;
switch (id) { // argument 'id' is the row of the clicked item
case FIRST_ROW:
sound = MediaPlayer.create(sonidos.this, R.raw.dtrain);
break;
case SECOND_ROW:
sound = MediaPlayer.create(sonidos.this, R.raw.bell);
break;
// and so on ...
}
if (sound.isPlaying()) {
sound.stop();
} else {
try {
sound.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}

Related

android play one sound at a time

I am stumped on this and I have referenced so many other posts. I'm not asking for anyone to complete my code but simply to point out where I'm going wrong and steer me into the right direction. I want to play an audio file when I click a image button but have it stop when another image button is clicked. The problem I'm having is if I press all the image buttons they will all play audio at the same time.
package com.application.cats.catsshapecolorapp;
import android.content.Context;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class ColorPage extends AppCompatActivity {
Context context = this;
MediaPlayer mpPurple,mpBlue,mpRed,mpGreen,mpYellow,mpPink;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_page);
mpPurple = MediaPlayer.create(context, R.raw.purpleaudiotest);
ImageButton purpleB = (ImageButton) findViewById(R.id.purpleButton);
purpleB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpPurple.isPlaying()) {
mpPurple.stop();
mpPurple.release();
mpPurple = MediaPlayer.create(context, R.raw.purpleaudiotest);
} mpPurple.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
mpBlue = MediaPlayer.create(context, R.raw.blueaudiotest);
ImageButton blueB = (ImageButton) findViewById(R.id.blueButton);
blueB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpBlue.isPlaying()) {
mpBlue.stop();
mpBlue.release();
mpBlue = MediaPlayer.create(context, R.raw.blueaudiotest);
} mpBlue.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
mpRed = MediaPlayer.create(context, R.raw.redaudiotest);
ImageButton redB = (ImageButton) findViewById(R.id.redButton);
redB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpRed.isPlaying()) {
mpRed.stop();
mpRed.release();
mpRed = MediaPlayer.create(context, R.raw.redaudiotest);
} mpRed.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
mpGreen = MediaPlayer.create(context, R.raw.greenaudiotest);
ImageButton greenB = (ImageButton) findViewById(R.id.greenButton);
greenB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpGreen.isPlaying()) {
mpGreen.stop();
mpGreen.release();
mpGreen = MediaPlayer.create(context, R.raw.greenaudiotest);
} mpGreen.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
mpYellow = MediaPlayer.create(context, R.raw.yellowaudiotest);
ImageButton yellowB = (ImageButton) findViewById(R.id.yellowButton);
yellowB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpYellow.isPlaying()) {
mpYellow.stop();
mpYellow.release();
mpYellow = MediaPlayer.create(context, R.raw.yellowaudiotest);
} mpYellow.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
mpPink = MediaPlayer.create(context, R.raw.pinkaudiotest);
ImageButton pinkB = (ImageButton) findViewById(R.id.pinkButton);
pinkB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpPink.isPlaying()) {
mpPink.stop();
mpPink.release();
mpPink = MediaPlayer.create(context, R.raw.pinkaudiotest);
} mpPink.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
}
update: now the problem is the pinkaudiotest is always the first audio file to play no matter what image button I click. I have to click a second time to hear the correct audio file.
You are creating a new MediaPlayer instance every click. Simply use a single one.
if (media.isPlaying()) {
media.stop();
media.release();
media= MediaPlayer.create(context, R.raw.purpleaudiotest);
} media.start();

how to play sound in android

I want to play music in my app when application starts. I tried many codes but nothing is working for me and i'm not getting any error.Can somebody please help me regarding this issue.Thanks in advance.
public class Login extends Activity {
EditText edName, edPassword;
String userName,password;
MediaPlayer mp;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mp = MediaPlayer.create(getApplicationContext(), R.raw.startsound);
ActionBar actionBar = getActionBar();
actionBar.hide();
edName = (EditText) findViewById(R.id.editText1);
edPassword = (EditText) findViewById(R.id.editText2);
mp.start();
}
public void SignInClick(View V) {
userName = edName.getText().toString();
password = edPassword.getText().toString();
if (userName.equals("")) {
Toast.makeText(Login.this, "Username is empty", Toast.LENGTH_LONG).show();}
else if (password.equals("")) {
Toast.makeText(Login.this, "Password is empty", Toast.LENGTH_LONG).show();
}
else {
Intent intent=new Intent(Login.this,Home.class);
startActivity(intent);
}
}
Hope this helps, and should be a working example although I have not had chance to test it.
public static Music theme;
theme = createMusic("menutheme.mp3");
theme.setLooping(true);
theme.setVolume(0.85f);
theme.play();
public Music createMusic(String filename) {
try {
AssetFileDescriptor assetDescriptor = assets.openFd(filename);
return new AndroidMusic(assetDescriptor);
} catch (IOException e) {
throw new RuntimeException("Couldn't load music '" + filename + "'");
}
}
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import com.matt.framework.Music;
import java.io.IOException;
public class AndroidMusic implements Music, OnCompletionListener, OnSeekCompleteListener, OnPreparedListener, OnVideoSizeChangedListener {
MediaPlayer mediaPlayer;
boolean isPrepared = false;
public AndroidMusic(AssetFileDescriptor assetDescriptor) {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
assetDescriptor.getStartOffset(),
assetDescriptor.getLength());
mediaPlayer.prepare();
isPrepared = true;
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnVideoSizeChangedListener(this);
} catch (Exception e) {
throw new RuntimeException("Couldn't load music");
}
}
#Override
public void dispose() {
if (this.mediaPlayer.isPlaying()){
this.mediaPlayer.stop();
}
this.mediaPlayer.release();
}
#Override
public boolean isLooping() {
return mediaPlayer.isLooping();
}
#Override
public boolean isPlaying() {
return this.mediaPlayer.isPlaying();
}
#Override
public boolean isStopped() {
return !isPrepared;
}
#Override
public void pause() {
if (this.mediaPlayer.isPlaying())
mediaPlayer.pause();
}
#Override
public void play() {
if (this.mediaPlayer.isPlaying())
return;
try {
synchronized (this) {
if (!isPrepared)
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void setLooping(boolean isLooping) {
mediaPlayer.setLooping(isLooping);
}
#Override
public void setVolume(float volume) {
mediaPlayer.setVolume(volume, volume);
}
#Override
public void stop() {
if (this.mediaPlayer.isPlaying() == true){
this.mediaPlayer.stop();
synchronized (this) {
isPrepared = false;
}}
}
#Override
public void onCompletion(MediaPlayer player) {
synchronized (this) {
isPrepared = false;
}
}
#Override
public void seekBegin() {
mediaPlayer.seekTo(0);
}
#Override
public void onPrepared(MediaPlayer player) {
// TODO Auto-generated method stub
synchronized (this) {
isPrepared = true;
}
}
#Override
public void onSeekComplete(MediaPlayer player) {
// TODO Auto-generated method stub
}
#Override
public void onVideoSizeChanged(MediaPlayer player, int width, int height) {
// TODO Auto-generated method stub
}
}

Android media player progress bar rest to "0" when stop music

I put one song into an app (tabhost) and I have progress bar, play button, stop button, loop button.
The function I want is:
when user plays the music, the progress bar starts to run from "0"
when user presses stop, the progress bar stops at where it was, waits for the user to press play again, and then continues where it left off
I might change the button name to "pause" later, but this is the function I need right now.
Right now, 2 issues:
When stop is pressed, the progress bar returns to "0", but the music resumes playing from where it left off (music not playing from very beginning)
The progress bar runs faster than desired; it runs to the end before the music ending.
Here is my code, hope someone could help thank you so much:
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import java.util.logging.LogRecord;
public class TabMusicActivity extends Activity {
MediaPlayer mediaPlayer;
private boolean playing = false;
private ProgressBar progressBar;
private Handler handler = new Handler();
int progress = 0;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
final ImageButton buttonStart = (ImageButton)findViewById(R.id.buttonStart);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!playing) {
playing = true;
buttonStart.setImageResource(R.drawable.music_stop_button);
Uri path = Uri.parse("android.resource://"+getPackageName()+"/"+ R.raw.bashibafo);
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(TabMusicActivity.this, path);
}
if (mediaPlayer != null) {
mediaPlayer.start();
process();
}
}
else {
playing = false;
buttonStart.setImageResource(R.drawable.button_play);
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
}
});
ImageButton buttonLoop = (ImageButton)findViewById(R.id.buttonLoop);
buttonLoop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.setLooping(true);
}
});
}
private void process (){
progressBar.setProgress(0);
progress = 0;
new Thread(new Runnable() {
#Override
public void run() {
while (progress < 100){
progress = doWork();
try{
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post( new Runnable() {
#Override
public void run() {
progressBar.setProgress(progress);
}
});
}
}
}).start();
}
private int doWork(){
progress++;
if (progress < 100){
return progress;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 100;
}
#Override
protected void onDestroy() {
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
super.onDestroy();
}
}
I used this code for playing music
if (player != null)
{
player.seekTo(length);
player.start();
}
else
{
player = MediaPlayer.create(context, Uri.fromFile(new File(url)));
seek_bar.setMax(player.getDuration());
seek_bar.setProgress(player.getCurrentPosition());
player.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
player.reset();
player.release();
player = null;
seekHandler.removeCallbacks(run);
seek_bar.setProgress(0);
if (recieveOrSend.equals("send"))
{
holder.iv_audio_pause_send.setVisibility(View.INVISIBLE);
holder.iv_audio_play_send.setVisibility(View.VISIBLE);
}
else
{
holder.iv_audio_pause_recieve.setVisibility(View.INVISIBLE);
holder.iv_audio_play_recieve.setVisibility(View.VISIBLE);
}
}
});
// player.prepare();
player.start();
}
seekUpdation();
Methods--
Runnable run = new Runnable()
{
#Override
public void run()
{
seekUpdation();
}
};
public void seekUpdation()
{
seek_bar.setProgress(player.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
}
private void pausePlayer()
{
try
{
if (player != null)
{
player.pause();
length = player.getCurrentPosition();
seekHandler.removeCallbacks(run);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

Correct method to use MediaPlayer in android app

sorry my english, but I'm from Brazil and I used the google translator.
Well, I'm struggling in this application where I am trying to make a streaming an online radio, works fine in version 2.2, but version 4.0 does not work. No error occurs, simply does not work. Below is my code.
I appreciate any help.
package com.radiomiriam;
import java.io.IOException;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class Main extends Activity {
public String url = "http://69.64.48.96:9880";
public MediaPlayer player = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void stop(){
Toast.makeText(getApplicationContext(), "Finalizando...", Toast.LENGTH_SHORT).show();
if(player.isPlaying()){
player.stop();
}
}
public void play(){
if(player.isPlaying()){
Toast.makeText(getApplicationContext(), "Já está em execução!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Preparando...", Toast.LENGTH_SHORT).show();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
try {
player.setDataSource(url);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.start();
}
}
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.btnPlay:
play();
break;
case R.id.btnStop:
stop();
break;
}
}
}
Hello, excuse my insistence but I still have not found the solution to my problem and do not know how to solve, I have once again asking for your help to solve this problem.
The application runs in versions 2.x and 3.x but not in version 4.x. Below is a link to download the project, to which you can take a look and help me.
http://nsi.inf.br/RadioMiriam.rar (removed)
i downloaded your project and it actually returns error Code:
E/MediaPlayer( 1976): error (-38, 0)
It is caused by starting mediaplayer before it is prepared.
I have made few changes and it started to work. You should :
Set onPrepared listener on MediaPlayer (i.e. in onCreate)
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
Remove player.start() from your play() method
Set datasource in this way (in your play() method)
player.setDataSource(this, Uri.parse("http://69.64.48.96:9880/"));
It works on my HTC Sensation with Android 4.0.3
If you need any assistance please let me know.
EDIT: i forgot, i also removed
player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
It is redundant
The prepare() call is probably blocking the UI thread (which android 4.0 hates it when you do that)
You will need to this work in a background thread like an asynctask. Here is a anonymous version of implementing AsyncTask to run play() in the background.
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.btnPlay:
new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... voids) {
play();
return null;
}
}.execute();
break;
case R.id.btnStop:
stop();
break;
}
}
You will need to read up a bit about MediaPlayer's states (playing, preparing, stopped, etc) to learn why calling prepare will block the UI thread (
for more info on AsyncTasks
You haven't set any link between buttons in your .xml file and your code. onClick method is never called even though you are pressing the buttons.
Replace your onCreate method with this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button playButton = (Button) findViewById(R.id.btnPlay);
playButton.setOnClickListener(this);
Button stopButton = (Button) findViewById(R.id.btnStop);
stopButton.setOnClickListener(this);
play();
}
It is always better in android to do any IO work on a background thread.
And that includes MediaPlayer . but in MediaPlayer case you already have prepareAsync() method to prepare the MediaPlayer in the background for you.
A good way to do that is like this:
package com.radiomiriam;
import java.io.IOException;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class Main extends Activity implements OnPreparedListener{
public String url = "http://69.64.48.96:9880";
public MediaPlayer player = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void stop(){
Toast.makeText(getApplicationContext(), "Finalizando...", Toast.LENGTH_SHORT).show();
if(player.isPlaying()){
player.stop();
}
}
public void play(){
if(player.isPlaying()){
Toast.makeText(getApplicationContext(), "J? est? em execuç?o!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Preparando...", Toast.LENGTH_SHORT).show();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
try {
player.setDataSource(url);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
player.setOnPreparedListener(this);
player.prepareAsync();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
}
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.btnPlay:
play();
break;
case R.id.btnStop:
stop();
break;
}
}
}
Also it is always a good practice to read the documentations, so here is a link to MediaPlayer API : MediaPlayer

MediaPlayer Android

I want to use MediaPlayer android, using this code, but I get an error, there's a way to fix this code, or can anyone bring me a better example for this?
try {
MediaPlayer player = new MediaPlayer();
player.setDataSource("/LFP/res/raw/Allen.mp3");
player.prepare();
player.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.media.MediaPlayer.OnPreparedListener;
import android.view.MotionEvent;
import android.widget.MediaController;
import android.widget.TextView;
import java.io.IOException;
public class AudioPlayer extends Activity implements OnPreparedListener,
MediaController.MediaPlayerControl{
private static final String TAG = "AudioPlayer";
public static final String AUDIO_FILE_NAME = "audioFileName";
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player);
audioFile = this.getIntent().getStringExtra(AUDIO_FILE_NAME);
((TextView)findViewById(R.id.now_playing_text)).setText(audioFile);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
try {
mediaPlayer.setDataSource(audioFile);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + audioFile + " for playback.", e);
}
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return false;
}
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.main_audio_view));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
}
This worked fine for me.Hope it works for you also.
use
mediaplayer.prepareAsync()
and
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
instead it
Here I am keeping my audio file in asset. Following code works,
MediaPlayer mp= new MediaPlayer();
AssetFileDescriptor afd = null;
try {
afd =getActivity().getBaseContext().getAssets().openFd("myAudio.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources