我只是使用翻新功能下载视频文件并将其转换为tempFile,但是将其转换后将无法播放视频。
这就是我所做的。
@Streaming
@GET("media/attachment")
fun getAttachmentFromMedia(): Observable<ResponseBody>
fun getAttachment() {
getApi().getAttachmentFromMedia()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
if (fileType.contains("image")) {
//.. some stuff here
} else if (fileType.contains("video")) {
val tmpFile = File.createTempFile("default", ".mp4")
tmpFile.deleteOnExit()
try {
val output = FileOutputStream(tmpFile)
var read = 0
output.use { _ ->
val buffer = ByteArray(4 * 1024)
while (it.byteStream().read(buffer).let { read = it; read != -1 }) {
output.write(buffer, 0, read)
}
output.flush()
}
} finally {
it.byteStream().close()
val mediaController = MediaController(holder.itemView.context)
mediaController.setAnchorView(holder.videoView)
holder.videoView.setMediaController(mediaController)
holder.videoView.setVideoURI(Uri.fromFile(tmpFile))
holder.videoView.start()
holder.videoView.visibility = View.VISIBLE
}
}
},
{
Log.e(TAG, "getAttachment failed", it)
}
)
}
当附件为图片时,此代码有效,但是在视频中,我真的不知道为什么视频无法播放。
我也不知道为什么在调用此getAttachmentFromMedia()
API时,应用程序暂时冻结了。
我在这里做对吗,还是应该更改一些内容?
感谢您的帮助。谢谢。
答案 0 :(得分:0)
VideoView videoView;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView = (VideoView)findViewById(R.id.ViewVideo);
String videopath = "android.resource://com.example.cloudanalogy.play_video/"+R.raw.a; //com.example.cloudanalogy.play_video this is my package name,and inside the raw file a.mp4 video
Uri vidUri = Uri.parse(videopath);
videoView.setVideoURI(vidUri);
videoView.start();
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
}
}
答案 1 :(得分:0)
在设备中下载文件后,像这样从file_path播放视频。
将以下代码放入您的finally块中。
MediaController mediaController = new MediaController(getActivity());
mediaController.setMediaPlayer(videoView);
videoView.setVideoURI(Uri.parse(mFilePath));
videoView.setMediaController(mediaController );
videoView.start();
直接从video_url播放视频。
try {
pDialog.show();
MediaController mediacontroller = new MediaController(this);
mediacontroller.setAnchorView(videoview);
Uri video = Uri.parse(VideoURL);
videoview.setMediaController(mediacontroller);
videoview.setVideoURI(video);
videoview.requestFocus();
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
videoview.start();
}
});
} catch (Exception e) {
pDialog.dismiss();
e.printStackTrace();
}