正在 android 上播放声音

Playing a sound on android

我在第一次使用应用程序时遇到了另一个错误:) 我想在应用程序加载时播放声音。这是一个 .wav 文件。它持续 2 秒长,但当我 运行 我的旧三星 S4 上的应用程序时它不播放。 IDE 或我能看到的任何内容都没有错误,我检查了 'mp' 是否有值并且确实有。环顾四周的帖子,大多数人都会遇到 'mp' is = null 的问题。而我的值只是 phone 没有声音...再次感谢您的帮助!

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

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

播放器应该可以工作。

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

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

为什么用final? 您可以使用

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

另外,如果您在 onDestroy 中停止,则停止 mediaplayer 会更好。

   public void onDestroy() {

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

}