在线播放mp4

在线播放mp4

1、准备好支持再网页上播放的mp4格式

AVC(h264) 格式的mp4

 

2、用ckplayer控制播放

(1)到ckplayer下载js。如:http://www.ckplayer.com/down/

(2)到flask工程中写html静态代码

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello flask</title>
</head>
<body>
<h1>hello flask2</h1>

<script type="text/javascript" src="js/ckplayer/ckplayer.js"></script>
<div class="videosamplex">
    <video id="videoplayer" src="http://127.0.0.1:5000/static/p42.mp4"></video>
</div>
<script type="text/javascript">
    var videoObject = {
	container: '.videosamplex',//“#”代表容器的ID,“.”或“”代表容器的class
	variable: 'player',//该属性必需设置,值等于下面的new chplayer()的对象
	poster:'pic/wdm.jpg',
	mobileCkControls:true,//是否在移动端(包括ios)环境中显示控制栏
	mobileAutoFull:false,//在移动端播放后是否按系统设置的全屏播放
	h5container:'#videoplayer',//h5环境中使用自定义容器
	video:'http://127.0.0.1:5000/static/p42.mp4'//视频地址
    };
    var player=new ckplayer(videoObject);
</script>
</body>
</html>

  

3、用flask暴露mp4服务

# -*- coding: utf-8 -*-
from  flask import Flask

app = Flask(__name__)


@app.route('/')
def index():
    return "hello flask"


if __name__ == '__main__':
    app.run()

  

 

转载于:https://www.cnblogs.com/andy9468/p/10869803.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Netty来处理在线播放mp4请求,下面是大致的实现思路: 1. 创建一个Netty服务器,监听指定的端口,等待客户端连接。 2. 当有客户端连接时,创建一个ChannelPipeline,添加一系列的ChannelHandler,用于处理请求和响应。 3. 当收到客户端的请求时,解析请求中的URL,获取要播放mp4文件的路径。 4. 使用Java的NIO API读取mp4文件,将数据写入响应的Channel中,实现流式传输。 5. 客户端收到响应后,使用HTML5的video标签播放mp4文件,实现在线播放。 示例代码如下: ```java public class Mp4StreamingServer { private final int port; public Mp4StreamingServer(int port) { this.port = port; } public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new Mp4StreamingServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = Integer.parseInt(args[0]); new Mp4StreamingServer(port).run(); } } ``` ```java public class Mp4StreamingServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> { private static final String CONTENT_TYPE = "Content-Type"; private static final String CONTENT_LENGTH = "Content-Length"; private static final String KEEP_ALIVE = "keep-alive"; @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (request.method() != HttpMethod.GET) { sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } String uri = request.uri(); String path = sanitizeUri(uri); if (path == null) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } File file = new File(path); if (!file.exists() || file.isHidden() || !file.isFile()) { sendError(ctx, HttpResponseStatus.NOT_FOUND); return; } if (!file.canRead()) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } RandomAccessFile raf = new RandomAccessFile(file, "r"); long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); if (HttpUtil.isKeepAlive(request)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ctx.write(response); ChannelFuture sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise()); sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) throws Exception { if (total < 0) { System.err.println("Transfer progress: " + progress); } else { System.err.println("Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { System.err.println("Transfer complete."); } }); ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!HttpUtil.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*"); private String sanitizeUri(String uri) { try { uri = URLDecoder.decode(uri, "UTF-8"); } catch (UnsupportedEncodingException e) { try { uri = URLDecoder.decode(uri, "ISO-8859-1"); } catch (UnsupportedEncodingException e1) { throw new Error(); } } if (!uri.startsWith("/")) { return null; } uri = uri.replace('/', File.separatorChar); if (uri.contains(File.separator + '.') || uri.contains('.' + File.separator) || uri.startsWith(".") || uri.endsWith(".") || INSECURE_URI.matcher(uri).matches()) { return null; } return System.getProperty("user.dir") + File.separator + uri; } private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } private static void setContentTypeHeader(HttpResponse response, File file) { MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); response.headers().set(CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath())); } } ``` 在上面的示例代码中,Mp4StreamingServer类是启动Netty服务器的入口,它创建了一个ServerBootstrap实例,配置了NioEventLoopGroup、NioServerSocketChannel、ChannelInitializer和Mp4StreamingServerHandler等组件,并监听指定的端口,等待客户端连接。 Mp4StreamingServerHandler类是处理请求和响应的核心,它继承了SimpleChannelInboundHandler<FullHttpRequest>,重写了channelRead0方法,用于读取客户端的请求,解析请求中的URL,获取要播放mp4文件的路径,读取mp4文件并将数据写入响应的Channel中,实现流式传输。同时,如果客户端请求中包含keep-alive头,则在响应中添加该头,以保持连接,避免浪费资源。最后,通过调用ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)方法,通知客户端数据传输完成,释放资源。 总之,使用Netty来处理在线播放mp4请求,可以提高服务器的并发处理能力和吞吐量,同时实现实时流媒体传输,提升用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值