mremremre1 mremremre1 - 5 months ago 7
Android Question

Play a sound from res/raw

I m making an app which is supposed to play a few sounds with the mediaPlayer.
This is the code i use :

String[] name = {"sonar_slow","sonar_medium","sonar_fast"};
String link = "/res/raw/" + name[state-1] + ".mp3";

try {
player.setDataSource(link);
player.prepare();
player.start();
} catch(Exception e) {
e.printStackTrace();
}


I also tried this :

if(state==1){
player.create(this, R.raw.sonar_slow);
}else if(state==2){
player.create(this, R.raw.sonar_medium);
}else if(state==3){
player.create(this, R.raw.sonar_fast);
}
player.start();


But none of the above is working. My app is not crashing but the sound is not playing.
Any ideas ?

Answer

There are two problems.

Problem 1

You cannot reference resources inside your projects /res/raw directory in this fashion. The file "/res/raw/sonar_slow.mp3" in your project directory is not stored in "/res/raw/sonar_slow.mp3" in your apk. Instead of the following:

MediaPlayer mp = MediaPlayer.create(this);  
mp.setSource("sonar_slow");

You need to use

MediaPlayer mp = MediaPlayer.create(this, R.raw.sonar_slow); 

Problem 2

The following is wrong: it calls a static method that does not modify the player.

player.create(this, R.raw.sonar_slow); 

You should instead call

player = MediaPlayer.create(this, R.raw.sonar_slow);

Full solution

Below is a reusable AudioPlayer class that encapsulates MediaPlayer. This is slightly modified from "Android Programming: The Big Nerd Ranch Guide". It makes sure to remember to clean up resources

package com.example.hellomoon;

import android.content.Context;
import android.media.MediaPlayer;

public class AudioPlayer {

    private MediaPlayer mMediaPlayer;

    public void stop() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    public void play(Context c, int rid) {
        stop();

        mMediaPlayer = MediaPlayer.create(c, rid);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                stop();
            }
        });

        mMediaPlayer.start();
    }

}