String path ="";
mediaPlayer.setDataSource(path); //path url mp3
mediaPlayer.prepare();
textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
Example read all mp3 in the folder download or specific path
It will be better if you explain you question more. As far as I understand your questing, you want to loop your media player.
if you want to loop your media player then add
mediaPlayer.setLooping(true);
I think that you are asking about how to add data source path. So, if you are asking that, than try this:
String path = Environment.getExternalStorageDirectory()+"/Download/music.mp3";
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
And if you are asking about loop media play then:
mediaPlayer.setLooping(true);
read all mp3 & m4a & wav & aac in the folder Music :
private int trackIndex = 0;
private List<String> tracks;
private MediaPlayer mediaPlayer;
private void initMediaPlayer() {
tracks = new ArrayList<>();
addTracksInDirectory("/storage/emulated/0/Music/");////path url mp3
mediaPlayer = new MediaPlayer();
setTrack(trackIndex);
}
private void setTrack(int index) {
try {
trackIndex = index;
mediaPlayer.reset();
mediaPlayer.setDataSource(tracks.get(trackIndex));
mediaPlayer.prepare();
mediaPlayer.start();
// Listen for the end of the track and play the next one
mediaPlayer.setOnCompletionListener(mediaPlayer -> {
trackIndex = (trackIndex + 1) % tracks.size();
setTrack(trackIndex);
});
} catch (IOException e) {
// Handle the error
}
}
private void addTracksInDirectory(String directoryPath) {
File directory = new File(directoryPath);
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && isAudioFile(file.getName())) {
tracks.add(file.getAbsolutePath());
}
}
}
}
private boolean isAudioFile(String fileName) {
String[] audioFileExtensions = {".mp3", ".m4a", ".wav", ".aac"};
for (String extension : audioFileExtensions) {
if (fileName.endsWith(extension)) {
return true;
}
}
return false;
}
First of all create a list and add all the songs.
final ArrayList<String> playList = new ArrayList<String>();
// Add yours songs to the list that needs to be played NEXT.
Now add a completion listener for the playlist, so after current song is completed it will play the next.
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if(playList.size() == 0) return; // played all so return.
String path = playList.remove(0); // get & remove the song from the playlist we are gonna play.
// Play the song
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
}
});
Related
I'm using JavaFX to create a media player, and everything works fine, but I have a small issue, when I call mediaPlayer.play() after I paused the audio/video, I get a weird sound glitch, like the audio plays, then pauses por like 100ms and then plays again, normally.
my code looks like this
choosing a file
public void chooseFileClicked(ActionEvent e) {
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(null);
path = file.toURI().toString();
if (mediaPlayer != null) {
mediaPlayer.stop();
}
if (path != null) {
media = new Media(path);
mediaPlayer = new MediaPlayer(media);
playButton.setDisable(false);
playButton.setSelected(true);
try { // if its a video
mediaView.setMediaPlayer(mediaPlayer);
mediaView.fitHeightProperty().bind(screenBackground.widthProperty());
mediaView.fitWidthProperty().bind(screenBackground.heightProperty());
}
catch(Exception ex) { // if its audio, get other stuff
//
}
mediaPlayer.play();
}
and the pause/play
public void playButtonClicked(ActionEvent e) {
if (playButton.isSelected()) {
mediaPlayer.play();
}
else {
mediaPlayer.pause();
}
}
I tried searching on internet about this, but I can't find any information about it.
I don't know if this is just a sound glitch that happens because I'm in the IDE and everything is slower there, or if this really its a bug in my program and it can be fixed
If someone can help me with this problem:
I'm trying to get the song from res folder in this method
private void playSound(String file) {
Context context = binding.playBtn.getContext();
Resources resources = context.getResources();
int sound_id = resources.getIdentifier(file,"raw",
context.getPackageName());
MediaPlayer mediaPlayer = MediaPlayer.create(context,sound_id);
mediaPlayer.start();
}
Then to call this method here
public void bind(CalmScreenItem calmScreenItem) {
binding.mainText.setText(calmScreenItem.mainText);
binding.subtext.setText(calmScreenItem.subtext);
binding.itemImg.setImageDrawable(getImage(calmScreenItem.imgUrl));
binding.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playSound(calmScreenItem.soundUrl);
}
});
}
Then finally call in the main fragment in the list**
private List<CalmScreenItem> getItems() {
List<CalmScreenItem> calmScreenItems = new ArrayList<>();
calmScreenItems.add(new CalmScreenItem(getString(R.string.main_item1),getString(R.string.sub_item1),"guide","free.mp3"));
calmScreenItems.add(new CalmScreenItem(getString(R.string.main_item2),getString(R.string.sub_item2),"mindfull","mindfull.mp3"));
return calmScreenItems;
}
The output should be when clicked on button to play different sound from the res folder
Can someone please help me! Thanks
There is a mistake in the way you are fetching the files
YOu would need to use an Uri and pass that to the MediaPlayer for it to be able to play your music . Also store y our audio files in raw subdirectory
For eg:
Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.filename);
try {
mMediaPlayer.setDataSource(getApplicationContext(), mediaPath);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
Ref : StackOverflow questionon playing music from raw resource
I am creating an android app from android studio.
My intention is to have a function to play different songs depending on the string argument.
MediaPlayer mysound;
public void play(String song){
mysound = Mediaplayer.create(this, "../../../../asset/soundlib/" + song);
mysound.play();
}
I tried the R.assets.song. It just does not work.
Is there a way to have the song named C.mp3? It says that they should not be capitalized and all of the arguments taken are basically chords like C A F...
Thank you
For android java use
void test_mp(String file_name)
{
MediaPlayer mediaPlayer = null;
mediaPlayer = new MediaPlayer();
try {
AssetFileDescriptor afd = act.getAssets().openFd(file_name);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepare();
} catch (final Exception e) {
e.printStackTrace();
}
mediaPlayer.start();
}
So for your case, you can call it like test_mp("SoundLib/A.mp3");
Try below code for play assets song :
fun playSound(context: Context, assetsFileName: String?) {
try {
val mediaPlayer = MediaPlayer()
val descriptor: AssetFileDescriptor = context.getAssets().openFd(assetsFileName!!)
mediaPlayer.setDataSource(
descriptor.getFileDescriptor(),
descriptor.getStartOffset(),
descriptor.getLength()
)
descriptor.close()
mediaPlayer.prepare()
mediaPlayer.isLooping = false
mediaPlayer.start()
} catch (e: Exception) {
e.printStackTrace()
}
}
Thanks
Here I have created an app to take images and save them to external storage of the phone. (Also there is a problem with below code that images are not saved to the given location.) I want only the last taken image to be saved in external memory of the phone.Everytime I take a new picture, I need to delete the previously taken image and save only the last taken image. How can I do it? Also is it possible to take images continously at regular intervals? I searched and I found that I can do it with a Timer(). Is it possible? Thank You.
Edit- Actually what I want is to comapare two images. One is taken at the moment and other is taken immediately before it. (I take images at regular time intervals and I compare new one with the previous one.) Only after comparison, I delete previous one.
public class MyCamera extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* #return
*/
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, e.getMessage());
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String fname = "IMG_" + timeStamp + ".jpg";
System.out.println(fname);
File mediaFile;
mediaFile = new File(mediaStorageDir, fname);
return mediaFile;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_camera, menu);
return true;
}
}
You can keep a constant name for your photo file.
String fname = "MyImage.jpg";
You can give some constant name. And about taking image at regular interval, you can use handler.
You can read more about it here.
And make sure your remove your handler when your camera is closed.
EDITED
You can list the files of your directory,mediaStorageDir in your case.
List all the files of the directory, and delete the file which is older by comparing the last modified.
I have some mp3 files on a cloud service.The links are like that https://dns/mp3filename.mp3?dl=1. I can play the files streaming with Vlc media player and I can write the bytes in files in Java. But when I try to play the links in Android media player some times it plays some times I get error(1,-1004) that is media_error_io.
Streaming code:
mp.setDataSource(link);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepareAsync();
mp.setWakeMode(ctx, PowerManager.PARTIAL_WAKE_LOCK);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
I have been looking for a library but I could not found one. I just came with the idea about download the file and play it while downloading, but the media player only reads the first bytes I give it to play and called setOnCompletionListener even if the file have been completely downloaded.
That code is in a thread and it's for download the file
try {
File cacheDir = new File(ctx.getCacheDir().getPath()+"/"+"mp3s");
cacheDir.mkdir();
File tempFile = File.createTempFile("mp3" + num, ".mp3", cacheDir);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(tempFile));
HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(lien).openConnection();
httpURLConnection.setDoInput(true);
BufferedInputStream bufferedInputStream = new BufferedInputStream(httpURLConnection.getInputStream());
byte bytes[] = new byte[1048576];
int len = 0;
int nbre = 0;
int current = 0;
while ((len = bufferedInputStream.read(bytes))!=-1){
bufferedOutputStream.write(bytes,0,len);
bufferedOutputStream.flush();
nbre+= len;
current += len;
onLoadingListener.onLoading(current, httpURLConnection.getContentLength());
if(nbre >= 524288){
nbre = 0;
onReadyListener.onReady(tempFile);
}
}
bufferedOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
onReadyListener.onReady(tempFile); is callback to start the media player like that.
playerMediaDownloader.setOnReadyListener(new PlayerMediaDownloader.OnReadyListener() {
#Override
public void onReady(final File file) {
path = file.getPath();
try {
if(!playing) {
Log.d(getClass().getSimpleName(), "li ready");
mp.setDataSource(file.getPath());
mp.prepare();
mp.start();
Log.d(Player.this.getClass().getSimpleName(), "pos:"+mp.getCurrentPosition());
playing = true;
for (OnTimeChanged l : onTimeChangeds) {
l.onTimeChanged(mp.getCurrentPosition(), mp.getDuration());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
The media player finished to play the file when it reach the 524288 bytes even if the file has been completely downloaded.
I came with another solution that is set the file file again and play it and it worked but, the sound cut a bit and it is not pretty like that.
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
int currentPosition = mp.getCurrentPosition();
mp.reset();
try {
Player.this.mp.setDataSource(path);
mp.prepare();
mp.seekTo(currentPosition);
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
Log.d(getClass().getSimpleName(), "fini jwe:"+mp.getCurrentPosition());
}
});
Do you have a better solution to help me make it works fine please, like playing the file asynchronously?