我爱编程

Android play background music an

2018-04-12  本文已影响35人  赶时间的闹钟
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RawRes;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;
    SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mediaPlayer = playBackgroundMusic(this, R.raw.audio_bg, true);

        findViewById(R.id.main_play_audio).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                soundPool = playSoundPoolAudio(R.raw.audio_pup_window);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
        }
        soundPool.autoResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
        soundPool.autoPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
    }

    private MediaPlayer playBackgroundMusic(Context context, @RawRes int res, boolean loop) {
        MediaPlayer mp;
        mp = MediaPlayer.create(context, res);
        mp.setLooping(loop);
        mp.start();
        Toast.makeText(context, "Play background music!", Toast.LENGTH_SHORT).show();
        return mp;
    }

    private SoundPool playSoundPoolAudio(@RawRes int res) {

        AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
        assert am != null;
        float currentStreamVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        float maxStreamVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float setVolume = currentStreamVolume / maxStreamVolume;

        SoundPool sp;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            sp = new SoundPool.Builder()
                    .setMaxStreams(3)
                    .build();
        } else {
            sp = new SoundPool(3, AudioManager.STREAM_MUSIC, 1);
        }
        HashMap<String, Integer> hm = new HashMap<>();
        hm.put("audio_1", sp.load(this, res, 0));
        sp.play(hm.get("audio_1"), setVolume, setVolume, 1, 0, 1.0f);

        Toast.makeText(MainActivity.this, "Play audio! ", Toast.LENGTH_SHORT).show();
        return sp;
    }

}

上一篇下一篇

猜你喜欢

热点阅读