Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

android - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...