使用 videoview 播放带音频文件的视频

using videoview to play video with audio file

我的目标是通过单击按钮播放视频文件(也有音频);但是不知怎么的,只有视频显示没有音频。

我的MainActivity.java:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    VideoView mVideoView=(VideoView) findViewById(R.id.videoView);
  //mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    Button button=(Button) findViewById(R.id.play_button);
    button.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View view){
            String uriPath="android.resource://com.example.android.happybirthday/"+R.raw.video_2;
            VideoView mVideoView=(VideoView) findViewById(R.id.videoView);
            Uri uri =Uri.parse(uriPath);
            mVideoView.setVideoURI(uri);
            mVideoView.requestFocus();
            mVideoView.start();
            mVideoView.setMediaController(new MediaController(MainActivity.this));
            mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.setVolume(0,0);
                }
            });
        }
    }); 
 }

我的activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.happybirthday.MainActivity">

<Button
    android:text="Play"
    android:id="@+id/play_button"
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<VideoView
    android:id="@+id/videoView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

您必须设置媒体播放器的音量。您可以先设置侦听器 videoView.setOnPreparedListener(preparedListener);,然后在 preparedListener 的方法 public void onPrepared(MediaPlayer m) { 中设置所需的音量 m.setVolume(0f, 0f);

内联侦听器示例:

videoview.setOnPreparedListener(new OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.setVolume(0, 0);
    }
});