Tuesday, 9 April 2019

How to play audio from mp3 array [Android]

Working on a testing project, my current objective is to use an int to specify which mp3 file to be played upon the initialization of the app without knowing the name of soundtracks beforehand (Scalability issue as I want to be able to add new mp3 files to the randomization pool without touching the code in future). However, when I run the following code, an error occurred with the following description:

error: no suitable method found for create(MainActivity,String) method MediaPlayer.create(Context,Uri) is not applicable (argument mismatch; String cannot be converted to Uri) method MediaPlayer.create(Context,int) is not applicable (argument mismatch; String cannot be converted to int)

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.widget.ArrayAdapter;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView bensonRecycler;
    ArrayList<String> arrayList;

    ArrayAdapter bensonAdapter;
    MediaPlayer bensonPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AssetManager assetManager = getAssets();
        String[] audios = assetManager.list("sound");

        int i = 1;

        final MediaPlayer mp = MediaPlayer.create(this, audios[i]);
        mp.start();

    }
}

My assets of mp3 files have the following structure:

enter image description here

So my question is what should I do in order to use the int i to specify which mp3 soundtrack to play (without knowing name of mp3 soundtracks beforehand) among the array of mp3 assets? (I must use a variable to specify the soundtrack to play in this testing project)



from How to play audio from mp3 array [Android]

No comments:

Post a Comment