使用视频视图播放带有音频文件的视频



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

我的主要活动.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);然后您可以在方法public void onPrepared(MediaPlayer m) {中设置所需的音量preparedListenerm.setVolume(0f, 0f);

内联侦听器示例:

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

最新更新