简体   繁体   中英

android studio media player null object reference

I ran into trouble when trying to use the media player in Android Studio, it seems like i haven't initialize the media player properly, which caused the app to crash (on phones running on Android 8.0) when SoundFXPlayer.setVolume() function is called. However, the app worked properly in emulator (API 26 - 28) , and most of the phone i tested (phones with on API 26-27) , EXCEPT phones that run on Android 8.0 (API 28) . To summarize 1. How to initialize media player properly 2. Why my code work on emulator but not on phone.

i am new to stackoverflow and not experienced in programming, sorry if didn't gave enough details.

Error message as follow:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.garmischwong.buttongame/com.example.garmischwong.buttongame.MenuActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setVolume(float, float)' on a null object reference

package com.example.garmischwong.buttongame;

import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class MenuActivity extends AppCompatActivity {

private Button gameButton;
public int SoundFXVolume;
public MediaPlayer SoundFXPlayer;
public static final String GAME_PREF = "gamePref" ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);
    gameButton = findViewById(R.id.gameButton);
    SoundFXPlayer = MediaPlayer.create(this, R.raw.menu_selection_click);
    loadSoundFX();
    SoundFXPlayer.setVolume((float)SoundFXVolume/100,(float)SoundFXVolume/100);
}


public void goToGameAct(View view)
{
    //////Intent to game///////
    SoundFXPlayer.start();
    Intent goToGameIntent = new Intent(MenuActivity.this, GameActivity.class);
    startActivity(goToGameIntent);
    finish();
}

public void loadSoundFX()
    {
        SharedPreferences gamePref = getSharedPreferences(String.valueOf(GAME_PREF), MODE_PRIVATE);
        SoundFXVolume = gamePref.getInt("Sound_FX_Volume", 30);
    }

Most likely audio format is not being supported. You can use 8bit and 16bit linear PCM. Here is more information on supported media formats: supported media formats

The solution is to re-encode the mp3 files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM