Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you play a mp3 file from the assets folder?

Tags:

android

I store all my sounds in the res folder. I'm wondering if there is a way to store them in the assets folder and play them from there?

This is the code I'm using now:

void StartSound(int id) {
    if (id==0)
        return;

    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    // float volume = actualVolume / maxVolume;
    float volume=(float) ( .01*(double)cGlobals.iVol);

    // Is the sound loaded already?
    if (nLastSound!=0)
        soundPool.stop(nLastSound); 

    int t=soundPool.play(id, volume, volume, 1, 0, 1f);
    nLastSound=t;
}

I want to change this to avoid a memory error when the APK tries to load. If I remove some of the files from the res folder it works fine. I'm hopping I want have the same issue if they are saved as a file.

like image 766
Ted pottel Avatar asked May 28 '13 15:05

Ted pottel


People also ask

How do I play audio files on Android?

Prepare media file: To play a media file, you need to first prepare it i.e. you need to load the file for playback. Methods used for doing this are prepare(), prepareAsync(), and setDataSource(). Start/Pause the playback: After loading the media file, you can start playing the media file by using the start() method.

Where do I put mp3 files in Android Studio?

Step 1: Open the android studio with the project in which you want to add-on audio clip/media file. Step 2: Create a raw folder. Step 3: Add media file to raw folder by simply copy and paste that to raw folder.

How do I add files to assets folder?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 – Create a new Assets folder and write a new text file in it.


2 Answers

You can do it in another way too. Put the .mp3 files under res/Raw folder and use the following code:

MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.android);
mediaPlayer.start();
like image 69
Bharat Jyoti Avatar answered Sep 30 '22 04:09

Bharat Jyoti


private void startSound(String filename){
    AssetFileDescriptor afd = getAssets().openFd(filename);
    MediaPlayer player = new MediaPlayer();
    player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    player.prepare();
    player.start();
}
like image 45
Charlie-Blake Avatar answered Sep 30 '22 03:09

Charlie-Blake