This is how I am doing this.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next: {
currentFile = input.get(currentPosition + 1);
if (mediaPlayer != null) {
mediaPlayer.release();
}
try{
mediaPlayer.setDataSource(currentFile);
mediaPlayer.reset();
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
case R.id.prev: {
currentFile = input.get(currentPosition - 1);
if (mediaPlayer != null) {
mediaPlayer.release();
}
try {
mediaPlayer.setDataSource(currentFile);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
Can't play the next and previous buttons. I want to play next and previous track from raw folder. I tried to do so but I am unable to do this. Give some suggestions. Thank You...
Related
So I have a .mp3 in assets folder (I plan to have many more later) and I have a simple click associated to play it:
public static MediaPlayer m = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button= (Button) findViewById(R.id.btnDrum);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PlayMusic(v);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void PlayMusic(View v) throws IOException {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd(Kit.KickDrum);
m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
m.prepare();
m.setVolume(1f, 1f);
m.setLooping(true);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}
However, every-time I try to click the button, I the music plays in loop! I just need it to play once and stop! How can this be done?
Thanks!
you are setting it for looping using m.setLooping(true); change it to false
try this code
try {
Uri mp3 = Uri.parse("url");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(context, mp3);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(onCompletionListener);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// onCompletionListerner
private OnCompletionListener onCompletionListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.release();
mediaPlayer = null;
}
};
I have a small radio app, I'm trying to get it to keep trying to reconnect/buffer my stream forever without quiting... not sure how I can loop this, but this is my buffering code. Any kind of help I can get on this is greatly appreciated!
public void prepare() {
/* ------Station- buffering-------- */
isPreparingStarted = true;
setStatus(STATUS_BUFFERING);
sendBroadcast(new Intent(MODE_THREE));
showNotification();
try {
if (getCurrentStationType().equals(SIGNAL_AAC))
multiPlayer.playAsync(StationURL());
else {
mediaPlayer.setDataSource(StationURL());
mediaPlayer.prepareAsync();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
stop();
} catch (NullPointerException e) {
e.printStackTrace();
stop();
} catch (IllegalStateException e) {
e.printStackTrace();
stop();
} catch (IOException e) {
e.printStackTrace();
stop();
} catch (Exception e) {
e.printStackTrace();
stop();
}
}
The app I am working on takes JSONs from a server and has to interpret them. I have around 6-7 JSONs that are requested.
As such, this is bound to take some time.
This code runs whenever the user types in information to an EditText and clicks a button. After the search button is clicked, the app freezes and will not do anything until all the data is loaded.
I tried having the code like this:
Button button = (Button) findViewById(R.id.search_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(summonerNameET.getWindowToken(), 0);
final CollectUserData c = new CollectUserData();
c.setRegion(region);
c.setSummonerName(summonerNameET.getText().toString());
Runnable r = new Runnable() {
#Override
public void run() {
try {
c.setUpTheJSONs();
updateUI(c);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
};
r.run();
}
});
But it still freezes. Here is the code for setUpTheJSON();
public void setUpTheJSONs() throws IOException, JSONException, URISyntaxException {
jsonSummonerInfo = getJsonSummonerInfo();
if(canIContinue()) {
jsonSummonerStats = getJsonSummaryStats();
//jsonSummonerRankedStats = getJsonRankedStats();
jsonSummonerMatchHistory = getJsonMatchHistory();
jsonSummonerLeagueInfo = getJsonSummonerLeagueInfo();
jsonSummonerRecentGames = getJsonSummonerRecentGames();
}
}
And here is the code for unpdateUI(c);
public void updateUI(CollectUserData c) {
if (c.canIContinue()) {
String league = "";
try {
league = c.getMundaneCurrentLeague();
} catch (JSONException e) {
e.printStackTrace();
}
setLeague(tierIV, league);
try {
summonerNameTV.setText(c.getSummonerName());
} catch (JSONException e) {
e.printStackTrace();
}
try {
tierTV.setText(c.getTier());
} catch (JSONException e) {
e.printStackTrace();
}
try {
leaguePointsTV.setText(c.getLeaguePoints() + "");
} catch (JSONException e) {
e.printStackTrace();
}
try {
winsTV.setText("W: " + c.getWins());
} catch (JSONException e) {
e.printStackTrace();
}
slashTV.setText("/");
try {
lossesTV.setText("L: " + c.getLosses());
} catch (JSONException e) {
e.printStackTrace();
}
try {
lastSeasonRankTV.setText("Season 4: " + c.getRankOfLastSeason());
} catch (JSONException e) {
e.printStackTrace();
}
try {
gameModeGameOneTV.setText(c.getGameType(1));
} catch (JSONException e) {
e.printStackTrace();
}
try {
gameOneChampion.setBackground(c.getChampionPicturePlayed(1));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneKillsTV.setText(c.getKills(1) + "");
} catch (JSONException e) {
e.printStackTrace();
}
gameOneSlashOneTV.setText(" / ");
try {
gameOneDeathsTV.setText(c.getDeaths(1) + "");
} catch (JSONException e) {
e.printStackTrace();
}
gameOneSlashTwoTV.setText(" / ");
try {
gameOneAssistsTV.setText(c.getAssists(1) + "");
} catch (JSONException e) {
e.printStackTrace();
}
try {
gameOneGoldTV.setText(c.getGold(1) + " K");
} catch (JSONException e) {
e.printStackTrace();
}
try {
gameOneCSTV.setText(" " + c.getMinionsKilled(1) + " CS");
} catch (JSONException e) {
e.printStackTrace();
}
boolean gameOneWon = true;
try {
gameOneWon = c.isGameWon(1);
} catch (JSONException e) {
e.printStackTrace();
}
if (gameOneWon) {
gameOneTitleBar.setBackgroundColor(Color.parseColor("#d604c429"));
gameOne.setBackgroundColor(Color.parseColor("#4600FF06"));
}
if (!gameOneWon) {
gameOneTitleBar.setBackgroundColor(Color.parseColor("#d6ff0100"));
gameOne.setBackgroundColor(Color.parseColor("#4fff0100"));
}
try {
gameOneItemOneIV.setBackground(c.getItemFromMatchHistory(1, 0, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneItemTwoIV.setBackground(c.getItemFromMatchHistory(1, 1, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneItemThreeIV.setBackground(c.getItemFromMatchHistory(1, 2, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneItemFourIV.setBackground(c.getItemFromMatchHistory(1, 3, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneItemFiveIV.setBackground(c.getItemFromMatchHistory(1, 4, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneItemSixIV.setBackground(c.getItemFromMatchHistory(1, 5, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Drawable[] tempDrawable = null;
try {
tempDrawable = c.getTeamPlayerChampionIcon(1, 100);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (tempDrawable != null) {
gameOneTeamOnePlayerOne.setBackground(tempDrawable[0]);
gameOneTeamOnePlayerTwo.setBackground(tempDrawable[1]);
gameOneTeamOnePlayerThree.setBackground(tempDrawable[2]);
gameOneTeamOnePlayerFour.setBackground(tempDrawable[3]);
gameOneTeamOnePlayerFive.setBackground(tempDrawable[4]);
}
Drawable[] tempDrawable2 = null;
try {
tempDrawable2 = c.getTeamPlayerChampionIcon(1, 200);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (tempDrawable != null) {
gameOneTeamTwoPlayerOne.setBackground(tempDrawable2[0]);
gameOneTeamTwoPlayerTwo.setBackground(tempDrawable2[1]);
gameOneTeamTwoPlayerThree.setBackground(tempDrawable2[2]);
gameOneTeamTwoPlayerFour.setBackground(tempDrawable2[3]);
gameOneTeamTwoPlayerFive.setBackground(tempDrawable2[4]);
}
String[] tempString = null;
try {
tempString = c.getTeamPlayerName(1, 100);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (tempString != null) {
gameOneTeamOnePlayerOneName.setText(tempString[0]);
gameOneTeamOnePlayerTwoName.setText(tempString[1]);
gameOneTeamOnePlayerThreeName.setText(tempString[2]);
gameOneTeamOnePlayerFourName.setText(tempString[3]);
gameOneTeamOnePlayerFiveName.setText(tempString[4]);
}
String[] tempString2 = null;
try {
tempString2 = c.getTeamPlayerName(1, 200);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (tempString2 != null) {
gameOneTeamTwoPlayerOneName.setText(tempString2[0]);
gameOneTeamTwoPlayerTwoName.setText(tempString2[1]);
gameOneTeamTwoPlayerThreeName.setText(tempString2[2]);
gameOneTeamTwoPlayerFourName.setText(tempString2[3]);
gameOneTeamTwoPlayerFiveName.setText(tempString2[4]);
}
}
}
Anyone know a fix for this?
Thanks ☺
You need to introduce multi threading. The r.run() command needs to be started by another thread.
http://developer.android.com/training/multiple-threads/index.html
You are running the Runnable in the UI Thread and this is why you are getting your UI blocked until it finished.
Try something like this:
Button button = (Button) findViewById(R.id.search_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(summonerNameET.getWindowToken(), 0);
final CollectUserData c = new CollectUserData();
c.setRegion(region);
c.setSummonerName(summonerNameET.getText().toString());
new Thread(new Runnable() {
#Override
public void run() {
try {
c.setUpTheJSONs();
updateUI(c);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}).start();
}
});
Put your downloading files in a separate thread. Use AsyncTask or Java Thread. Just simply.
class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Show progress dialog, if u want
}
#Override
protected Void doInBackground(Void... params) {
//Do all your processing here!
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Return some result to UI
}
}
I have listview, mediaplayer and mediacontroller. I'd like to make mediaplayer play stream musics from url when I touch list in listview.
My problem is mediaplayer plays only one song. When I touch second list while playing first list audio, it does not play second list audio.But I do not know the cause, mediaplayer plays second audio while playing first audio, when mediacontroller hides.
I want mediaplayer to stop and play another audio while mediacontroller shows and plays audio.
I tried two patterns, but these were same result.Please teach me what is wrong and sorry bad english skill.First pattern.
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
switch (position) {
case 0:
try {
mp.reset();
mp.setDataSource(url);
mp.prepare();
} catch (IllegalArgumentException e) {
//
e.printStackTrace();
} catch (IllegalStateException e) {
//
e.printStackTrace();
} catch (IOException e) {
//
e.printStackTrace();
}
break;
case 1:
try {
mp.reset();
mp.setDataSource(url2);
mp.prepare();
} catch (IllegalArgumentException e) {
//
e.printStackTrace();
} catch (IllegalStateException e) {
//
e.printStackTrace();
} catch (IOException e) {
//
e.printStackTrace();
}
break;
case 2:
try {
mp.reset();
mp.setDataSource(url3);
mp.prepare();
} catch (IllegalArgumentException e) {
//
e.printStackTrace();
} catch (IllegalStateException e) {
//
e.printStackTrace();
} catch (IOException e) {
//
e.printStackTrace();
}
break;
}
Second pattern.
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
try {
mp.reset();
mp.setDataSource(url[position]);
mp.prepare();
} catch (IllegalArgumentException e) {
//
e.printStackTrace();
} catch (IllegalStateException e) {
//
e.printStackTrace();
} catch (IOException e) {
//
e.printStackTrace();
}
Preparedlistner.
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
handler.post(new Runnable() {
#Override
public void run() {
controller.setEnabled(true);
controller.show(mp.getDuration());
mp.start();
try {
Method m = android.widget.MediaController.class.getDeclaredMethod("updatePausePlay");
m.setAccessible(true);
m.invoke(controller);
} catch (Exception e) {
}
}
});
}
});
}
onCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_songs);
ItemBean sample1 = new ItemBean();
fishing.setName("sample1");
ItemBean sample2 = new ItemBean();
hana.setName("sample2");
ItemBean sample3 = new ItemBean();
takane.setName("sample3");
List<ItemBean> list = new ArrayList<ItemBean>();
list.add(sample1);
list.add(sample2);
list.add(sample3);
sampleurl = getResources().getStringArray(R.array.sampleurl);
mp = new MediaPlayer();
controller = new MediaController(this);
controller.setAnchorView(findViewById(R.id.mediaController));
controller.setMediaPlayer(this);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
samplelist = (ListView) findViewById(R.id.song_list);
SonglistAdapter_test adapter = new SonglistAdapter_test(getApplicationContext(),list);
samplelist.setAdapter(adapter);
samplelist.setOnItemClickListener(this);
}
Do you call mcontroller = new MediaController(context); and doClean() somewhere? Most likely the controller needs to be reset before you put a new media source. Add this before your handler.post(new Runnable() {:
doClean();
mcontroller = new MediaController(getActivity());//or this, depending whats your context
public void playClickSound() {
AssetFileDescriptor afd;
MediaPlayer sound = new MediaPlayer();
try {
sound.setAudioStreamType(AudioManager.STREAM_MUSIC);
afd = getAssets().openFd("click.mp3");
sound.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
sound.prepare();
sound.start();
} catch (IllegalStateException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
This is my code for playing sound. I call this method on a few buttons in mu GUI.
It works fine the first time i press the button, but second time i get IllegalStateException.
What should I do to make this work?
You need to manage the life-cycle of the Media Player. Following the below flow, should work out:
RefreshPlayer()
{
if (mediaPlayer != null) {
{
mediaPlayer.stop();
mediaPlayer.reset();
}
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getSherlockActivity(),
Uri.fromFile(new File(VidPath)));
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (IllegalStateException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}