Is there a way to play mp3 files in one mediaplayer object? - java

I can play a sound using Mediaplayer class in java android.
I make a Mediaplayer object like this.
Mediaplayer mp=Mediaplayer.create(this,R.raw.mysong);
And then start it but what if i have more than one song and have to play it. Do I need to make objects for everyone of them. What i am trying to say is does Mediaplayer class have any kind of method or thing that i can clear the old song and put new song for playing?
Hope you get what i say
I could really appreciate it with a simple example.

Create only one object as you've done ,but like this
Mediaplayer mp = new MediaPLayer();
Change the data source:
If your source it’s a uri just pass it to setDataSource , but if is a resource in raw folder use this to create an uri from the resource
int resourceId = R.raw.other_song
uri uriSound = Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(resources.getResourcePackageName(resourceId))
.appendPath(resources.getResourceTypeName(resourceId))
.appendPath(resources.getResourceEntryName(resourceId))
.build()
mp.setDataSource(this , uriSound)
Prepare and start the media player when you want
mp.prepare()
mp.start()

You create your mediaplayer object without ".create" like this
Mediaplayer mp=new Mediaplayer();
Then you just set the source of it note the source must be in uri format
mp.setDataSource(this,uri);
But before starting it you have to prepare first like this:
mp.prepare();
Then start.
And when you wanted to change the source again first stop the mp then set another source
Hope you get it.

Related

Is it impossible to call mediaplayer.setpreparedlistener when mediapler.create method is used?

I'm trying to learn kotlin with a media player project in Android studio.
So I create a media player using create method.
val mediaplayer : MediaPlayer
mediaplayer= MediaPlayer.create(this,R.raw.song)
mediaplayer.start()
But the problem come when I use this:
mediaplayer.setOnPreparedListener(object: MediaPlayer.onPreparedListener{
override fun onPrepared(MediaPlayer mp){
val max = mp.max
Seekbar.max = max
textview.text = convertToSeconde(max) // a function I define
mp.start()
}
})
The problem is that, when I run the app my implementation of onpreparedlistener have never been called. And any error is raise to tell me what the cause.
Can you help me on this please?
No. It is not possible. But, why do you want to do so? It is prepared immediately after that file is created. But, in some cases it might not get prepared due to some issue with the file or uri. So, you can use this alternate after the .create() function:
if(mediaplayer != null){
// it was not created or prepared.
}else{
// good news. it got prepared successfully
}

JavaFX's Media Player not retrieving metadata

I'm creating a video player using JavaFX media player library. I need to retrieve the metadata and display in a window. I'm having problems retrieving the data though.
I've read 2 threads about this already and I understand that this is done asynchronously so I need a listener in order to get the metadata.
First Thread:Retrieving metadata from media files in JavaFX
Second Thread: https://stackoverflow.com/a/43144197/12787326
This code has been implemented like so below.
public void initialize(URL location, ResourceBundle resources) {
//Initialising path of the media file, replace this with your file path
String path = "Video.mp4";
//Instantiating Media class
Media media = new Media(new File(path).toURI().toString());
//Listener
media.getMetadata().addListener((MapChangeListener<String,Object>) change-> {
System.out.println(change);
});
//Instantiating MediaPlayer class
mediaPlayer = new MediaPlayer(media);
mv.setMediaPlayer(mediaPlayer);
mediaPlayer.setOnReady(() -> {
...
mediaPlayer.play();
});
}
I have tried a variety of different changes to the listener such as placing it in different areas of the code and trying to get the data from the mediaPlayer, which accesses the media itself. None of these seems to have fixed the problem.
I've tried print statements in the code trying to print off the contents of media.getMetadata but all I get is an empty list back.
I've tried creating a listener for media.getTracks() and that works as expected with updating each time the player switches its status. So that makes me wonder what is going wrong with media.getMetadata()
This is what the metadata of the video currently looks like so I assume I should be getting this infomarmation
I think the listener isn't seeing anything change, that's why print(change) is never reached. However, even if that is true, shouldn't me doing a system.out.print(media.getMetaData()) in the setOnAction code give me the data? Because when I try that all I get is an empty list.
Does anyone know how to fix this or tell me what I'm doing wrong?

Cannot play music from local filesystem, but can play from SD card

I am developing a test app that does nothing else than play music. The idea behind this app is that normally you have a music player that takes ages to load and has all those extra gadgets and gizmos that nobody, or at least not you, uses. This app only plays music, period. And it loads almost instantly.
But I got something funny. I need to find a way for the user to select a song from the filesystem, but I haven't got that working yet, so I am using a fixed song URI to play it. When I put this song on the local filesystem(i.e. /storage/emulated/0/Music/SongName.mp3), the app crashes upon pressing the play button. But when I put the song on the SD card(i.e. /storage/extSdCard/Music/SongName.mp3) it works fine.
Well, I got it to work, but I don't know how or why it works. Normally I would be surprised and not touch that piece of code again so that it keeps working, but this time I am learning programming on Android and I want to know why it works.
This is the code for playing from the SD card(works):
p = new MediaPlayer();
p.setAudioStreamType(AudioManager.STREAM_MUSIC);
p.setDataSource(getApplicationContext(), Uri.fromFile(new File("/storage/extSdCard/Tests/Take Back The Night.mp3")));
p.prepare();
p.start();
And this is the code for playing from the local fs(does not work):
p = new MediaPlayer();
p.setAudioStreamType(AudioManager.STREAM_MUSIC);
p.setDataSource(getApplicationContext(), Uri.fromFile(new File("/storage/emulated/0/Music/heybrother.mp3")));
p.prepare();
p.start();
As you can see, it's pretty much the same, so I concluded that there is probably something wrong in the URI. But I can't see any typos, and I retyped it multiple times. Is the URI malformed for this purpose?
I got it working!
First, you need to get the path of the music folder like this:
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
.getPath() + "/";
Then you can append the file name in the music folder:
String file = path + "ThatOneSong.mp3";
And then play it as normal. (Or you could do this in one long line but that's kind of cluttered.)

Possible to skip track from an Android application?

I'm planning on doing a application for Android 2.1 that changes song every minute (through what I hope exists in Android, "next") for the application using the audio device atm.
So if I have Spotify running in background already, playing music, can I through my program change to the next track?
Let me know if I was unclear about anything.
Thanks in advance!
I know this is a bit old question, but it took me some time searching something other then what is mentioned here.
There is a workaround - broadcasting media button action. There is one catch - receiver can recognize if the broadcast was from system or from another app, so they can ignore the non-system broadcasts.
Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
synchronized (this) {
i.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT));
sendOrderedBroadcast(i, null);
i.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_NEXT));
sendOrderedBroadcast(i, null);
}
There's no universal audio transport API for music applications, so you'd need to see if the music applications you're targeting publicly expose service bindings or intents. If not, you won't be able to do this.
Just posted a relevant answer here
Using the AudioManager's dispatchMediaKeyEvent() method with a defined KeyEvent worked for me using the latest SDK.
The system music homescreen widget sends this intent for the built-in music player:
final ComponentName serviceName = new ComponentName(context,
MediaPlaybackService.class);
intent = new Intent(MediaPlaybackService.NEXT_ACTION);
intent.setComponent(serviceName);
pendingIntent = PendingIntent.getService(context,
0 /* no requestCode */, intent, 0 /* no flags */);
views.setOnClickPendingIntent(R.id.control_next, pendingIntent);
But it looks like this might take some hackery to implement outside packages in the music app itself because the MediaPlaybackService only accepts explicit Intents and isn't accessible from the outside. This thread seems to indicate it's possible with a bit of hackery, though.
But even then, as Roman said, not every music player will respect that Intent. You'll have to check with Spotify/Pandora/Last.fm themselves and see if they have any available intents to bind like that.
Looks that it's possible to use AudioManager to inject media keys.
Here is a snippet from another question
this.mAudioManager = (AudioManager) this.context.getSystemService(Context.AUDIO_SERVICE);
long eventtime = SystemClock.uptimeMillis();
KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT, 0);
mAudioManager.dispatchMediaKeyEvent(downEvent);
KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_NEXT, 0);
mAudioManager.dispatchMediaKeyEvent(upEvent);
The same way you can inject PlayPause button and some others.
I've tested it within a background service controlling Youtube and it worked for Android 6

How to implement an audio player for Android using MediaPlayer And MediaController?

I want to create an Android application that is a client for an Internet radio station. And I want it look native to Android? But im confused with Android API logic and documentation. What i've got is that I need MediaPlayer and MediaController classes. Am I right, and is there any good example of AUDIO player for Android?
Especially, I'm very interested how to use MediaPlayer and MediaController classes together.
UPD:
Finally I've got the code, that does exactly what I want:
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(%file_uri%));
i.setData(u);
startActivity(i);
you can look at those links :
http://www.helloandroid.com/tutorials/musicdroid-audio-player-part-i
Hope it will help.
[EDIT]
You have also some example on the official android developer website :
http://developer.android.com/guide/topics/media/index.html

Categories