如何防止VideoView/MediaPlayer停止其他应用程序的音频? [英] How to prevent VideoView/MediaPlayer from stopping other apps' audio?

查看:668
本文介绍了如何防止VideoView/MediaPlayer停止其他应用程序的音频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个屏幕中,我有一个循环的背景视频(上面显示了普通的UI元素),该视频是通过VideoView实现的,如下所示:

String resPath = "android.resource://" + getPackageName() + "/" + R.raw.bg_video;
videoView.setVideoURI(Uri.parse(resPath));

// Hide controls:
MediaController controller = new MediaController(getActivity());
controller.setVisibility(View.GONE);
videoView.setMediaController(controller);

// Use looping:
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.setLooping(true);
    }
});

videoView.start();

视频效果很好.唯一的问题是,显示此视图时(甚至在使用ViewPager之前),其他应用程序的音乐播放会停止.

我正在使用的视频本身没有声音.有没有办法在静音模式"下设置VideoView或它使用的MediaPlayer?也就是说,告诉它根本不进行音频处理,尤其是不要与其他应用程序的音频混为一谈.

onPrepared()中尝试过mp.setVolume(0, 0);,但无效.

解决方案

从Android来源复制粘贴VideoView并注释掉以下几行:

AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

例如,您可以将新类命名为MutedVideoView.

要点在这里: https://gist.github.com/vishna/7e9d3466bced8502fcdd

In one screen I have a looping background video (upon which normal UI elements are shown), implemented with VideoView like this:

String resPath = "android.resource://" + getPackageName() + "/" + R.raw.bg_video;
videoView.setVideoURI(Uri.parse(resPath));

// Hide controls:
MediaController controller = new MediaController(getActivity());
controller.setVisibility(View.GONE);
videoView.setMediaController(controller);

// Use looping:
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.setLooping(true);
    }
});

videoView.start();

The video works great. The only problem is that when this view is shown (or even before if using e.g. ViewPager), music playback from other applications stops.

The video I'm using has no sound itself. Is there a way to set the VideoView, or the MediaPlayer it uses, in a "muted mode"? I.e., tell it not to do audio at all, and especially not to mess with other apps' audio.

Tried mp.setVolume(0, 0); in onPrepared() but it has no effect.

解决方案

Copy paste VideoView from Android sources and comment out these lines:

AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

You could name the new class MutedVideoView, for example.

gist here: https://gist.github.com/vishna/7e9d3466bced8502fcdd

这篇关于如何防止VideoView/MediaPlayer停止其他应用程序的音频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆