How To Load Music In Android With Libgdx?
Solution 1:
To load a Music instance we can do the following:
Music music = Gdx.audio.newMusic(Gdx.files.internal("data/mymusic.mp3"));
You can also use AssetManager to load your Music
so that you can manage your assets in proper way.
AssetManager manager = newAssetManager();
manager.load("data/mymusic.mp3", Music.class);
manager.finishLoading();
You can get your Music after assets have been successfully loaded.
Music music = manager.get("data/mymusic.mp3", Music.class);
Various Playback attributes that can use to play music
music.play();
Check this thread if you've some particular problem on Android. Some times Sound
may not play on Android devices but on desktop, it does play.
EDIT
Add this permission to AndroidMainfest.xml file.
<uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE" />
Make it clear for Android your targetSdkVersion is less than 23 if not take permission at run time by user before proceeding any work related to your File IO. For current targetSdkVersion check your defaultConfig of android build.gradle
file, if not present their check AndroidManifest.xml
file.
External Destination is address where we keep our own data like video, music and all.
Gdx.files.getExternalStoragePath() give path /storage/emulated/0/
in Android and User Directory on Desktop like this C:\Users\Abhishek Aryan\
/storage/emulated/0/
represent inbuilt Storage and Download is inside inbuilt storage.
if(Gdx.app.type==Application.ApplicationType.Android) {
var assetManager = AssetManager(ExternalFileHandleResolver())
var fileHandle = Gdx.files.external("/Download/WorldmapTheme.mp3")
if (fileHandle.exists()) {
assetManager.load(fileHandle.path(), Music::class.java)
assetManager.finishLoading();
var music = assetManager.get<Music>(fileHandle.path())
music.setLooping(true)
music.play()
}
}
EDIT 2
This code working fine for me, Hopefully this will work for you
// code inside create()
method of ApplicationListener
if(Gdx.app.getType()== Application.ApplicationType.Android) {
Stringfile="/download/prueba.mp3";
FileHandlefileHandle= Gdx.files.external(file);
SongFilesongFile=newSongFile(fileHandle);
songFile.parse();
song = songFile.makeSong();
}
Constructor of SongFile
class
publicclassSongFile {
AssetManager manager;
Music music;
publicSongFile(FileHandle file){
manager = new AssetManager(new ExternalFileHandleResolver());
if (file.exists()) {
manager.load(file.path(), Music.class);
manager.finishLoading();
music = manager.get(file.path(), Music.class);
music.setLooping(true);
music.play();
}
}
...
}
Post a Comment for "How To Load Music In Android With Libgdx?"