初学了一段时间Java。想做一个应用程序,程序只需要播放一个本地视频,MP4格式,求教怎么做
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了初学了一段时间Java。想做一个应用程序,程序只需要播放一个本地视频,MP4格式,求教怎么做相关的知识,希望对你有一定的参考价值。
装了eclipse。。。求代码,或者教程也行,只需要完成以上条件。。十分感谢,急求
使用javafx的Media,MediaPlayer,MediaView。代码如下:
import java.io.File;import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ReadOnlyProperty;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Slider;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application
private MediaView mediaView;
private Slider processSlider;
private static final Object AUTO = new Object(), MANUAL = new Object();
public static void main(String[] args)
launch(args);
@Override
public void start(Stage primaryStage) throws Exception
primaryStage.setTitle("javafx视频播放器");
BorderPane root = new BorderPane();
// 菜单栏
initMenu(root);
// 视频播放控件
mediaView = initMediaView(root);
// 视频功能控件
initMediaControllView(root);
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.setOnCloseRequest(event -> System.exit(0));
primaryStage.show();
private MenuBar initMenu(final BorderPane parent)
Menu menu = new Menu("菜单");
MenuItem item = new MenuItem("打开");
item.setOnAction(event ->
FileChooser chooser = new FileChooser();
chooser.setTitle("选择视频文件");
chooser.getExtensionFilters().add(new ExtensionFilter("视频文件", "*.mp4", "*.flv"));
File file = chooser.showOpenDialog(parent.getScene().getWindow());
if (file != null)
MediaPlayer player = mediaView.getMediaPlayer();
// 关闭当前的player
if (player != null)
player.stop();
player.dispose();
processSlider.setValue(0);
// 创建一个新的player并自动播放
player = new MediaPlayer(new Media(file.toURI().toString()));
player.currentTimeProperty().addListener(this::mediaProcessChanged);
player.setAutoPlay(true);
mediaView.setMediaPlayer(player);
);
menu.getItems().add(item);
item = new MenuItem("退出");
item.setOnAction(event -> parent.getScene().getWindow().hide());
menu.getItems().add(item);
MenuBar menuBar = new MenuBar(menu);
parent.setTop(menuBar);
return menuBar;
private MediaView initMediaView(final BorderPane parent)
MediaView view = new MediaView();
Pane pane = new Pane(view);
parent.setCenter(pane);
// 视频宽高可随着窗口变化而自动缩放
view.fitWidthProperty().bind(Bindings.selectDouble(view.parentProperty(), "width"));
view.fitHeightProperty().bind(Bindings.selectDouble(view.parentProperty(), "height"));
view.setPreserveRatio(true);
return view;
private void initMediaControllView(final BorderPane parent)
VBox bottom = new VBox(10);
bottom.setAlignment(Pos.CENTER);
parent.setBottom(bottom);
Slider slider = new Slider(0, 100, 0);
slider.valueProperty().addListener(this::processSliderChanged);
// slider.setOnMouseClicked(this::processSliderClicked);
bottom.getChildren().add(slider);
processSlider = slider;
HBox hbox = new HBox(10);
bottom.getChildren().add(hbox);
hbox.setAlignment(Pos.CENTER);
Button btn = new Button(null, new ImageView(loadImage("pause.png")));
btn.setOnAction(this::pauseOrPlay);
hbox.getChildren().add(btn);
btn = new Button(null, new ImageView(loadImage("stop.png")));
btn.setOnAction(this::stopPlay);
hbox.getChildren().add(btn);
private static Image loadImage(String resPath)
return new Image(Thread.currentThread().getContextClassLoader().getResourceAsStream(resPath));
private void pauseOrPlay(ActionEvent event)
MediaPlayer player = mediaView.getMediaPlayer();
if (player == null)
return;
Status status = player.getStatus();
if (status == Status.READY || status == Status.PAUSED)
player.play();
((Button) event.getTarget()).setGraphic(new ImageView(loadImage("pause.png")));
else if (status == Status.PLAYING)
player.pause();
((Button) event.getTarget()).setGraphic(new ImageView(loadImage("play.png")));
private void stopPlay(ActionEvent event)
MediaPlayer player = mediaView.getMediaPlayer();
if (player == null)
return;
player.stop();
// private void processSliderClicked(MouseEvent event)
// Slider slider = (Slider) event.getSource();
// if (mediaView.getMediaPlayer() != null)
// Duration d = mediaView.getMediaPlayer().getTotalDuration().multiply(slider.getValue() / slider.getMax());
// mediaView.getMediaPlayer().seek(d);
//
//
private void processSliderChanged(ObservableValue<? extends Number> observable, Number oldValue, Number newValue)
Slider slider = (Slider) ((ReadOnlyProperty<? extends Number>) observable).getBean();
if (slider.getUserData() == AUTO) // 进度条是自动改变的,因此不用设置播放器
slider.setUserData(null);
return;
if (mediaView.getMediaPlayer() != null)
slider.setUserData(MANUAL);
Duration d = mediaView.getMediaPlayer().getTotalDuration().multiply(newValue.doubleValue() / slider.getMax());
mediaView.getMediaPlayer().seek(d);
private void mediaProcessChanged(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue)
if (processSlider.getUserData() == MANUAL) // 手动点击进度条
processSlider.setUserData(null);
return;
MediaPlayer player = (MediaPlayer) ((ReadOnlyProperty<? extends Duration>) observable).getBean();
processSlider.setUserData(AUTO);
processSlider.setValue(newValue.toMillis() / player.getTotalDuration().toMillis() * 100);
参考技术A JAVA 对 视频的支持,太有限了。。。。。。。没法直接播放。
~
~
~
~
~ 参考技术B 把文件流,跟多媒体的那些资料先看熟再说。。求你妹的代码。。给你也看不懂。。估计追问
哦,多谢指点!
本回答被提问者采纳图像未显示在 Django 应用程序上
【中文标题】图像未显示在 Django 应用程序上【英文标题】:Images not showing on Django App 【发布时间】:2012-07-19 04:58:32 【问题描述】:我是一名 Django 初学者,正在尝试通过 lightbird.net 上的本教程来构建照片共享应用程序。我在让照片显示在开发服务器上时遇到问题。虽然我可以在管理界面上上传和保存图像,但照片也不会显示在那里。相反,我只看到一个 jpeg 图标。当我在开发服务器上查看页面时,会出现相同的 jpeg 图标而不是照片。
昨天我花了一段时间才安装 PIL 和 jpeg 库,虽然我的应用程序现在运行没有错误,但我怀疑图像不显示的原因与这两个安装之一有关。我认为这可能是浏览器问题,但我无法查看来自 firefox、google chrome 或 safari 的图像。
提前感谢您的帮助。这个网站太棒了!
代码的html是:
% extends "pbase.html" %
% block content %
<div class="main">
<!-- Albums -->
<ul>
% for album in albums.object_list %
<div class="title"> album.title ( album.image_set.count images)</div>
<ul>
% for img in album.images %
<a href=" media_url img.image.name "><img border="0"
src=" media_url img.thumbnail2.name " /></a>
% endfor %
</ul>
% endfor %
</ul>
<!--Next/Prev page links-->
% if albums.object_list and albums.paginator.num_pages > 1 %
<div class="pagination">
<span class="step-links">
% if albums.has_previous %
<a href= "?page= albums.previous_page_number ">previous <<</a>
% endif %
<span class="current">
Page albums.number of albums.paginator.num_pages
</span>
% if albums.has_next %
<a href="?page= albums.next_page_number "> >> next</a>
% endif %
</span>
</div>
% endif %
</div>
% endblock %
观点是:
def main(request):
albums = Album.objects.all()
if not request.user.is_authenticated():
albums = albums.filter(public=True)
paginator = Paginator(albums, 10)
try: page = int(request.GET.get("page", "1"))
except ValueError: page = 1
try:
albums = paginator.page(page)
except(InvalidPage, EmptyPage):
albums = paginator.page(paginator.num_pages)
for album in albums.object_list:
album.images = album.image_set.all()[:4]
return render_to_response("list.html", 'albums':albums, 'user':request.user, 'media_url':MEDIA_URL)
我的模型是:
class Album(models.Model):
title = models.CharField(max_length=60)
public = models.BooleanField(default=False)
def __unicode__(self):
return self.title
def images(self):
lst = [x.image.name for x in self.image_set.all()]
lst = ["<a href='/media/%s'>%s</a>" % (x, x.split("/")[-1])for x in lst]
return join(lst, ",")
images.allow_tags = True
class Tag(models.Model):
tag = models.CharField(max_length=60)
def __unicode__(self):
return self.tag
class Image(models.Model):
title = models.CharField(max_length=60, blank=True)
image = models.FileField(upload_to="images/")
tags = models.ManyToManyField(Tag, blank=True)
albums = models.ManyToManyField(Album, blank=True)
created = models.DateTimeField(auto_now_add=True)
rating = models.IntegerField(default=50)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
user = models.ForeignKey(User, null=True, blank=True)
thumbnail2 = models.ImageField(upload_to="images/", blank=True, null=True)
def save(self, *args, **kwargs):
"""save image dimensions."""
super(Image, self).save(*args, **kwargs)
im = PImage.open(os.path.join(MEDIA_ROOT, self.image.name))
self.width, self.height = im.size
# large thumb
fn, ext = os.path.splitext(self.image.name)
im.thumbnail((128,128), PImage.ANTIALIAS)
thumb_fn = fn + "-thumb2" + ext
tf2 = NamedTemporaryFile()
im.save(tf2.name, "JPEG")
self.thumbnail2.save(thumb_fn, File(open(tf2.name)), save=False)
tf2.close()
#small thumb
im.thumbnail((40,40), PImage.ANTIALIAS)
thumb_fn = fn + "-thumb" + ext
tf = NamedTemporaryFile()
im.save(tf.name, "JPEG")
self.thumbnail2.save(thumb_fn, File(open(tf.name)), save=False)
tf.close()
super(Image, self).save(*args, **kwargs)
def size(self):
return "%s x %s" % (self.width, self.height)
def tags_(self):
lst = [x[1] for x in self.tags.values_list()]
return str(join(lst, ', '))
def __unicode__(self):
return self.image.name
def albums_(self):
lst = [x[1] for x in self.albums.values_list()]
return str(join(lst, ', '))
def thumbnail(self):
return """<a href="/media/%s"><img border="0" src="/media%s" /></a>""" % (self.image.name, self.image.name)
thumbnail.allow_tags = True
【问题讨论】:
【参考方案1】:您可以使用img.image.url
获取图片字段的绝对网址。
我希望你已经提到
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.storage
How do I include image files in Django templates?
How to show an image in template uploaded from admin panel Django 1.3
【讨论】:
【参考方案2】:您可能还需要使用以下内容更新您的项目 urls.py:
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
'document_root': settings.MEDIA_ROOT)
【讨论】:
以上是关于初学了一段时间Java。想做一个应用程序,程序只需要播放一个本地视频,MP4格式,求教怎么做的主要内容,如果未能解决你的问题,请参考以下文章