如何限制android播放器并行播放多个媒体文件?

时间:2018-11-12 08:40:22

标签: android android-mediaplayer

如果我在其他应用中播放音乐,例如foob​​ar2000

然后使用此功能在我的应用程序中播放音乐,两个播放器将同时播放

public void playMusic(String file){
    Uri uri=Uri.parse("android.resource://" + getPackageName() + "/raw/"+file);

    if(uri!=null) {
        myPlayer = new MediaPlayer();
        if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                myPlayer.setAudioAttributes(new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build());
        }else{
            myPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        try {
            myPlayer.setDataSource(getApplicationContext(), uri);
        } catch (IllegalArgumentException e) {
        } catch (SecurityException e) {
        } catch (IllegalStateException e) {
        } catch (IOException e) {
        }
        try {
            myPlayer.prepare();
        } catch (IllegalStateException e) {
        } catch (IOException e) {
        }
        myPlayer.start();
    }
}

如果我先在应用中播放音乐,然后再播放其他播放器,其他播放器仍然无法停止我的播放器

如果我尝试另外两个播放器应用程序,它们可以彼此停止。

如何强制Android仅播放播放器,并允许其他播放器停止播放器?

1 个答案:

答案 0 :(得分:1)

您需要使用如下的AudioManager类, 每当您需要音频聚焦时,请调用以下方法

protected fun requestAudioFocus(): Boolean {
        val audioManager: AudioManager = binding.root.context.getSystemService(Context.AUDIO_SERVICE) as AudioManager

        val res = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
                    .setAudioAttributes(mPlaybackAttributes)
                    .setAcceptsDelayedFocusGain(true)
                    .setOnAudioFocusChangeListener(afChangeListener)
                    .build()
            audioManager.requestAudioFocus(mFocusRequest)
        } else {
            audioManager.requestAudioFocus(afChangeListener,
                    // Use the music stream.
                    AudioManager.STREAM_MUSIC,
                    // Request permanent focus.
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
        }
        return res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
    }

每当要发布它时,请使用以下代码

val audioManager: AudioManager = binding.root.context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                audioManager.abandonAudioFocusRequest(mFocusRequest)
            } else {
                audioManager.abandonAudioFocus(afChangeListener)
            }
        } catch (e: Exception) {

        }

清单中的u,您需要征得修改音频设置的许可

    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>

注意:-代码段位于Kotlin