在android上播放声音

时间:2017-04-17 22:05:54

标签: java android audio android-mediaplayer

我在第一次应用程序旅程中遇到了另一个错误:)我想在应用程序加载时播放声音。哪个是.wav文件。它持续2秒,但当我在旧的三星S4上运行应用程序时它不会播放。 IDE中没有任何错误或我能看到的任何内容,我已经检查过是否' mp'有价值,它有。在帖子上四处查看大多数人都有这样的问题:' mp'是= null。虽然我有一个价值,但手机没有声音......再一次,任何帮助都表示赞赏!

public class OpeningScreen extends Activity {
    @Override
    // create the screen state
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // connect the xml layout file
        setContentView(R.layout.activity_opening_screen);

        final MediaPlayer mp = new MediaPlayer();
        mp.create(this, R.raw.welcome_message);

        mp.start();

        // create the on touch listener
        ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.opening_layout);

        layout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // change the screen to a new state
                Intent intent = new Intent(OpeningScreen.this, GameScreen.class);

                // start the new activity
                startActivity(intent);

                // stop welcome sound (if still playing)
                mp.stop();
                return true;
            }
        });
    }
}

3 个答案:

答案 0 :(得分:0)

public static MediaPlayer create(Context context, int resid)是为给定资源ID创建MediaPlayer的静态方法。 这意味着通过调用create,您将创建一个没有引用的媒体播放器的新实例。

尝试更改

final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);

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

玩家应该工作。

答案 1 :(得分:0)

最好通过OnPreapredListener注册MediaPlayer.setOnPreaparedListener,并在准备好后开始播放媒体。

http://developer.android.com/guide/topics/media/mediaplayer.html

答案 2 :(得分:0)

为什么使用final? 你可以用

播放mp3
MediaPlayer mp = MediaPlayer.create(OpeningScreen.this, R.raw.welcome_message);
mp.start();

如果你停在onDestroy上,也可以更好地停止媒体播放。

   public void onDestroy() {

    mp.stop();
    super.onDestroy();

}