My project has a button. Each time the button is clicked I want to assign a new song to the media player. I'm running into error: cannot resolve method 'setDatSource(java.io.File)'
final MediaPlayer mPlayer1 = MediaPlayer.create(MainActivity.this, R.raw.bass);
b.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
try {
mPlayer.setDataSource(Environment.getExternalStorageDirectory());
}catch(Exception e){
e.printStackTrace();
}
return false;
}
});
Related
In my application I make a music background that works when click on a button start and the music changes loop sound1, sound2, sound3.
public void startNewGame() {//initializing the sounds
final MediaPlayer sound1 = MediaPlayer.create(this, R.raw.music1);
final MediaPlayer sound2 = MediaPlayer.create(this, R.raw.music2);
final MediaPlayer sound3 = MediaPlayer.create(this, R.raw.music3);
//generate random number
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(3) + 1;
//picking the right sound to play
switch (randomInt){
case 1:
if ( !sound1.isPlaying())
sound1.setLooping(true);
sound1.start();
break;
case 2: if ( !sound2.isPlaying() )
sound2.setLooping(true);
sound2.start();
break;
case 3:
if ( !sound3.isPlaying() )
sound3.setLooping(true);
sound3.start();
break;
}
mBtnChooseAndStart.setVisibility(View.GONE);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fl_board_container,
GameFragment.newInstance(mBitmapBricks, GOAL_STATUS))
.commit();
}
the pobelem is that when I click on another button start again that generates a dialogue after confirmation I start the game but with another sound that works and the first does not stop
how to solve this problem thanks in advance
public void restart(View view) {
if (mFullBitmap == null) {
// Not started, so cannot restart
UIUtils.toast(this, getString(R.string.not_started));
return;
}
new AlertDialog.Builder(this)
.setTitle(getString(R.string.restart))
.setMessage(getString(R.string.confirm_restart_msg))
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startNewGame();
}
})
.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
and also how to stop sounds in onBackpressed ().
finally I found the solution and it works
firstly create a method to stop mediaplayer
public void cleanUpMediaPlayer(){
if(mediaPlayer != null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
}
then create a method of launching for each sound and within this method it is necessary to apply the functin to stop mediaplayer if it exist
public void sound1(){
cleanUpMediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.music1);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
public void sound2(){
cleanUpMediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.music2);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
public void sound3(){
cleanUpMediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.music3);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
finally call the sounds in the desired moment
for me I want the sounds to change every time I play my game that's why I use random with switch loop like this.
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(3) + 1;
//picking the right sound to play
switch (randomInt){
case 1:
sound1();
break;
case 2:
sound2();
break;
case 3:
sound3();
break;
}
the same for onBackPressed() you just have to call cleanUpMediaPlayer method
public void onBackPressed() {
cleanUpMediaPlayer();
.....
}
a good day for my friend mistek :)
The ViewHolder I have contains views that are needed for each item of my RecycleView, which are two TextViews, PlayPauseView, and AppCompatSeekBar. In the constructor I have initialized them to their ids of my layout, and is ready for my Adapter class to extend it. The problem is I have this PlayPauseView that needs to be toggled at the correct position for it to function right, because if I press the view at another position, the previous position is still toggled. Here's an image for better understanding.
The yellow means that it is currently playing, but two cannot play at the same time so I was hoping to get the position of the view inside the RecyclerView item.
This is from the Holder class
TextView mInstrumentalName, mProducer;
PlayPauseView mPlayButton; // Need to add pause/stop
AppCompatSeekBar mMusicSeekbar;
ItemClickListener itemClickListener;
public TrackHolder(View itemView) {
super(itemView);
mInstrumentalName = (TextView) itemView.findViewById(R.id.instrumental_name);
mProducer = (TextView) itemView.findViewById(R.id.producer);
mPlayButton = (PlayPauseView) itemView.findViewById(R.id.play_pause);
mMusicSeekbar = (AppCompatSeekBar) itemView.findViewById(R.id.music_seekbar);
itemView.setOnClickListener(this);
}
This is from the Adapter class
#Override
public void onBindViewHolder(#NonNull final TrackHolder holder, final int position) {
holder.mInstrumentalName.setText(tracks.get(position).getInstrumentalName());
holder.mProducer.setText(tracks.get(position).getProducer());
holder.mPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.mPlayButton.toggle();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (mediaPlayer.isPlaying()) {
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(tracks.get(position).getMusicLink());
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} else {
try {
mediaPlayer.setDataSource(tracks.get(position).getMusicLink());
previous_link = tracks.get(position).getMusicLink();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
}
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
});
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Toast.makeText(context, Integer.toString(tracks.size()), Toast.LENGTH_SHORT).show();
}
});
}
If you want to get position in your view holder class then you can call getAdapterPosition() inside your class. this will return you the clicked position in view holder class
I finally found a solution. So what I did instead of focusing on the views inside of the ViewHolder, I refreshed/updated the whole item in the RecyclerView, meaning it will refresh the toggle state of the previous item. Here's a code snipped if anyone in the future has any trouble on the same question.
private int start_notifying = 0;
private int previous_pos = -1;
So start notifying is at 0 because you don't want to refresh the item until you toggled the play button at least once, and set the current position to become the previous position when you want to press a different list item. You then increment so you can start refreshing items on the next item pressed. Using notifyItemChanged(previous_pos) refreshed the item of the previous position that was pressed, making the play button go back to its normal state.
if (start_notifying > 0) {
notifyItemChanged(previous_pos);
previous_pos = position;
} else {
previous_pos = holder.getAdapterPosition();
Log.d("previous_pos", Integer.toString(holder.getAdapterPosition()));
start_notifying++;
}
Hi i have recyclerView row item consists of a play Button(Which change to stop and Play as toggle) and a play seek bar and TextView.
The each row plays different audios .
When i click on play button of respective row i am able to stop the other row audio ..
Addressing to the problem ..
When i am playing a audio of a respective row, the button of earlier row has to stow a play symbol (in the sense it has to change the state ) please help me how to update the other rows of recyclerView when the other item is clicked
#Override
public void onBindViewHolder(final ViewHolder holder, final int i) {
if (holder.viewType == ROW_TYPE){
// holder.play_button.setImageResource(R.drawable.play_button);
if(i == selected_item){
}
else {
// holder.play_button.setImageResource();
}
JSONObject obj;
String mp3_url = null, caption = null, thumbnail_url = null;
try {
obj = voicesArray.getJSONObject(i);
mp3_url = obj.getString("mp3_url");
caption = obj.getString("caption");
thumbnail_url = obj.getString("thumbnail_url");
} catch (JSONException e) {
e.printStackTrace();
}
holder.list_text.setText(caption);
imageLoader.DisplayImage(thumbnail_url, holder.list_image);
final String finalMp3_url = mp3_url;
holder.play_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selected_item = i;
int ii = holder.getOldPosition();
// holder.play_button.setImageResource();
// updateItem(ii);
if(player != null){
player.reset();
holder.play_button.setImageResource(R.drawable.play_button);
myAudioPlay(holder, finalMp3_url);
}
else {
myAudioPlay(holder,finalMp3_url);
/*if (player == null) {
player = new MediaPlayer();
playAudiFile(finalMp3_url);
holder.play_button.setImageResource(R.drawable.pause_button);
} else if (player.isPlaying()) {
holder.play_button.setImageResource(R.drawable.play_button);
player.stop();
Log.d("player", "" + player);
player.reset();
} else {
holder.play_button.setImageResource(R.drawable.pause_button);
playAudiFile(finalMp3_url);
}*/
}
}
});
}
}
Apparently the purpose of a recyclerView is to recycle the views to minimize memory usage required for rendering view so setting an image in the view is not an apt solution,Their are many solutions for your problem the One i would pick(Pseudo code) is given below
Step 1. Create a Boolean value in your model class
bool isPlay=true;
Step 2. When you are playing an audio loop through your Model for the recycler adapter and set the value for isPlay accourdingly
for(object obj in listOfModels)
if(obj.Id!=idOfthePlayingView)
obj.isPlay=false;
Then notify your adapter
yourRecyclerAdapterObject.notifyDatasetChanged()
I have created a listview which consists of list of tracks and play and pause image.When clicked on play image, pause image becomes visible and clicking on pause ,play image will become visible.Issue is that when i click on play and scrolls down i see another list item showing pause image and when i scroll down more another list item showing pause image.It is because list recylces an shows duplicated images.On studying the issue i think i need to place if-else statement in the getView method but i failed to implement correct code to resolve this issue..plzz help me with code in tht..
Create a new boolean variable in your SoundCloud class by the name isPlaying. Create getter setters for it, like you have done for other variables.
Get the object from SoundCloudList like this:
SoundCloug soundCloud = (SoundCloud) getItem(position);
This object can be used everywhere you are using soundcloudList.get(position), so that makes it easy to because we don't have to fetch object everytime.
Then in your getView use isPlaying to show play/pause button on every position like below:
if(soundCloud.isPlaying()){
holder.img1.setVisibility(View.VISIBLE);
holder.img2.setVisibility(View.GONE);
}
else{
holder.img1.setVisibility(View.GONE);
holder.img2.setVisibility(View.VISIBLE);
}
and then in your onClickListeners, set values for isPlaying like this:
holder.img1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(final View v) {
soundCloud.setPlaying(true);
try {
notifyDataSetChanged();
holder.img1.setVisibility(View.INVISIBLE);
holder.img2.setVisibility(View.VISIBLE);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource("http://api.soundcloud.com/tracks/" + soundcloudList.get(position).getId() + "/stream?client_id=e13865f9debacb5f96375fdd96b7fa1b");
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start();
}
});
mMediaPlayer.setOnCompletionListener(
new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mMediaPlayer.release();
mMediaPlayer = null;
holder.img1.setVisibility(View.VISIBLE);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
holder.img2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(final View v)
{
soundCloud.setPlaying(false);
notifyDataSetChanged();
holder.img1.setVisibility(View.VISIBLE);
holder.img2.setVisibility(View.INVISIBLE);
if(mMediaPlayer!=null)
{
mMediaPlayer.release();
mMediaPlayer = null;
}
}
});
This code will not show the play/pause button duplicated on multiple rows, because now, we are checking the play/pause of audio for every row in getView and only then setting the buttons visibility.
I have open a new project -
Now what I would like to do is this -
By pressing on the button I want an mp3 file being played - and also that each time the button is pressed than the sound file will start playing from the start of it once again - so let's say that the mp3 is 10 sec long, and I pressed the button and it's playing and after 4 sec I pressed the button again than the sound will be played again.
Now what I would like to know is-
1- Where should I put the mp3 file?
2-what code do I have to add in order that when the button is pressed than the mp3 file will be played (let's call the mp3 file click_sound.mp3)?
3- What I need to add to the code in order that the sound will be played again each time I will pressed the button?
This is the code of the MainActivity.java -
package com.example.test1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
}
and this is the activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/play" />
</RelativeLayout>
You should put mp3 file in /assets folder.
put this code inside onCreate() method after setContentView()
final MediaPlayer mp = new MediaPlayer();
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
}
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("AudioFile.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
3.sound will be played again each time you press button. You don't have to write any extra code for that.
Note that AudioFile.mp3 is the name of the mp3 file in /assets folder
Hope this answer is helpful:)
If you really have to invoke the click programmatically because the view has no own sound, i would solve it like that, its the simplest solution and a oneliner
view.playSoundEffect(SoundEffectConstants.CLICK);
very simple and works, if you want to make a layout play a sound you need to put
android:soundEffectsEnabled="true"
to the Layout
I think this is the pretty much what you wanted:
public class MainActivity extends Activity {
String tag;
static MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tag=getPackageName();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mp = new MediaPlayer();
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// MediaPlayer mp = new MediaPlayer();
if(!mp.isPlaying())
{
mp= new MediaPlayer();
}
try {
AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
/*b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
Log.e(tag,"mp is playing");
mp.stop();
mp.reset();
//mp.start();
}
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("AudioFile.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
// mp.release();
} catch (IllegalStateException e) {
Log.e(tag, e.toString());
//e.printStackTrace();
} catch (IOException e) {
Log.e(tag, e.toString());
//e.printStackTrace();
}
}
});
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
}
});*/
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I solved this like:
public void onClick(View v) {
sound.start();
if (sound.isPlaying()) {
sound.seekTo(0);
sound.start();
}
}
Hope this steps will help you to go ahead..
1.put your mp3 file under row folder (if not exist create one --> Right click on project ->new -> createfolder)
2.R&D ongoogle to play mp3 first (media player)
3.on click of button load that perticular file (by setting onclick listner to button)
best luck