简体   繁体   English

如何使用共享首选项使媒体静音

[英]How to mute media using shared pref

Hi guys in my app there is a sound that plays when the app starts up. 大家好,我的应用程序启动时会播放声音。 i want give people the option to mute this from the main activity settings screen. 我想让人们选择从主要活动设置屏幕上将此功能静音。

******Edit using answer given****** So i created a settings method in my main activity which now starts a new activity called Main2Activity this will be my settings activity once i get it working correctly. ******使用给出的答案进行编辑******因此,我在主活动中创建了一个设置方法,该方法现在启动一个名为Main2Activity的新活动,一旦我使其正常工作,这将是我的设置活动。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater=getMenuInflater();
    inflater.inflate(R.menu.menuitem, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.Settings:

///No longer inflates settings xml.. Starts new settings activity instead
           startactivity(new Intent(MainActivity.this,Main2Activity.class))
            break;
    }
    return super.onOptionsItemSelected(item);
}

then next i have my media player class 接下来我有我的媒体播放器课程

public class harropMediaplayer {
MediaPlayer mp;
String media;
public harropMediaplayer(String media){
   this.media = media;
}
public void plysound() {

///My media player is now stored globally as suggested 
    mp = App_Objects.mp;
    String j =
            media.toString();
    Log.i("Url", j);
    try {
        mp.setDataSource(j);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        mp.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

        Log.i("Sound playing", "Ok");

        mp.start();
    }

public void stopplying(){

    mp.stop();
    mp.release();
}

As suggested in the answer given ive now mad its so the media player can be accessed using a constraints class ive called App_Objects. 正如给出的ive的答案所建议的那样,现在可以使用名为App_Objects的约束类ive访问媒体播放器。

    public class App_Objects {

//This is where i store my media player

public static MediaPlayer mp = new MediaPlayer();
}

Next is my new SettingsActivity replacing my inflate view 接下来是我的新SettingsActivity替换了我的膨胀视图

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    final CheckBox btnradio = findViewById(R.id.btnmute);

    SharedPreferences sharedpreferences = getSharedPreferences("myPreference", Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = sharedpreferences.edit();
    btnradio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (btnradio.isChecked()){

                editor.putBoolean("soundMute", b);
                editor.apply();
                Log.i( "onCheckedChanged: ","Activated");

            }
            else {

                editor.clear();
                editor.apply();

                Log.i("onCheckChanged: ","Deactivated");
            }
        }
    });
}

and finally my splash activity where the start up sound plays via a firebase url which again ive added the answer given below. 最后是我的飞溅活动,其中启动声音通过firebase url播放,这再次为我添加了下面给出的答案。 including a method to mute the sound 包括使声音静音的方法

 setContentView(R.layout.activity_splash__screen);

    database = FirebaseDatabase.getInstance();
    reference = database.getReference().child("tvthemetunes");

    getthemetune();

}



public void getthemetune() {

    Log.i ("Url Grab ", "Started");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.i("Url Grab", "Searching database");
            long childrenCount = dataSnapshot.getChildrenCount();
            int count = (int) childrenCount;
            int randomNumber = new Random().nextInt(count);
            //Your random themeTune will be stored here
            for(DataSnapshot snap : dataSnapshot.getChildren())
            {
                int i =  0;

                    if(i == randomNumber)
                {
                    Themetune = snap.getValue(String.class);
                    try {

                        mp = new harropMediaplayer(Themetune);
                        ((TextView) findViewById(R.id.version)).setText("" + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
                        ImageView view = findViewById(R.id.splash);
                        ImageView view1 = findViewById(R.id.rain);
                        Animation animFadeIn = AnimationUtils.loadAnimation(Splash_Screen.this, R.anim.fadein);
                        animFadeIn.reset();
                        mp.plysound();
 ///HERE IS WHERE I CALL MY NEW METHOD
                         volumeSetting();

                        view1.clearAnimation();
                        view1.startAnimation(animFadeIn);
                        RotateAnimation anim = new RotateAnimation(0.0f, 
360.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

//Setup anim with desired properties
                        anim.setInterpolator(new LinearInterpolator());
                        anim.setRepeatCount(Animation.RELATIVE_TO_SELF); 
//Repeat animation indefinitely
                        anim.setDuration(1200); //Put desired duration per anim cycle here, in milliseconds

//Start animation
                        view.startAnimation(anim);

                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }


                    int secondsDelayed = 2;
                    new Handler().postDelayed(new Runnable() {
                        public void run() {


                            startActivity(new Intent(Splash_Screen.this, 
 MainActivity.class));
                            finish();
                            mp.stopplying();

                        }
                    }, secondsDelayed * 2000);



                    break;
                }

            }

            }





        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

 private void volumeSetting(){

////MY NEW VOLUME MUTE METHOD INCLUDING THE FETCH SHARED PREF
    SharedPreferences sharedpreferences = getSharedPreferences("myPreference", Context.MODE_PRIVATE);

    boolean bnSoundMute = sharedpreferences.getBoolean("soundMute",true);

    if(bnSoundMute){
        App_Objects.mp.setVolume(0,0); // for Mute
    }else{
        App_Objects.mp.setVolume(1,1);// for Unmute or full volume
    }
}
}

But now the sound seams to be muted. 但是现在声音接缝要静音了。 from the start and if i go to to my settings activity and click the mute startup check box then restart the app. 从头开始,如果我转到我的设置活动,然后单击“静音启动”复选框,然后重新启动应用程序。 The app crashes out giving my a fatal in my console 该应用崩溃了,这让我在控制台中丧命

AndroidRuntime: FATAL EXCEPTION: main
                                                                                    Process: h20music.p9p.harrop99.H20DroidApp_Amazon, PID: 2549
                                                                                    java.lang.IllegalStateException
                                                                                        at android.media.MediaPlayer.nativeSetDataSource(Native Method)
                                                                                        at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1078)
                                                                                        at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1039)
                                                                                        at h20music.p9p.harrop99.H20DroidApp_Amazon.harropMediaplayer.plysound(harropMediaplayer.java:29)
                                                                                        at h20music.p9p.harrop99.H20DroidApp_Amazon.Splash_Screen$1.onDataChange(Splash_Screen.java:84)
                                                                                        at com.google.android.gms.internal.zzeeq.zza(Unknown Source)
                                                                                        at com.google.android.gms.internal.zzegl.zzbwe(Unknown Source)
                                                                                        at com.google.android.gms.internal.zzegr.run(Unknown Source)
                                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

I got it what you want to do. 我明白了你想做什么。 you can achieve that by using declaring media player static. 您可以通过声明媒体播放器为静态来实现。 Below is the one of the way you can achieve this and you can well structure this code. 下面是实现此目标的一种方法,您可以很好地构造此代码。 I did't write code in details. 我没有写详细的代码。

Create AppConstants class and define MediaPlayer staticaly. 创建AppConstants类并静态定义MediaPlayer

public class AppConstants{

    public static MediaPlayer mp = new MediaPlayer();

}

Create SettingActivity Activity class where you can set sharedpreference value true/false for soundMute option. 创建SettingActivity活动类,您可以在其中为soundMute选项设置sharedpreference值true / false。

public class SettingActivity{

    SharedPreferences sharedpreferences = getSharedPreferences("myPreference", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();


    btnradio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            editor.putBoolean("soundMute", b);
            editor.apply();

        }
    });

}

Create SplashActivity Activity class where you can read sharedpreference to mute media player or not. 创建SplashActivity Activity类,您可以在其中读取sharedpreference来使媒体播放器静音。

public class SplashActivity{

    SharedPreferences sharedpreferences = getSharedPreferences("myPreference", Context.MODE_PRIVATE);

    boolean bnSoundMute = sharedpreferences.getBoolean("soundMute",true);

    if(bnSoundMute){
        AppConstants.mp.setVolume(0,0); // for Mute
    }else{
        AppConstants.mp.setVolume(1,1); // for Unmute or full volume
    }

    try {
        AppConstants.mp.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    AppConstants.mp.start();

} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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