使用Django和WebRTC可以创建一个简单的直播应用程序,这个示例包含基本的配置和代码。直播功能涉及实时通讯,因此需要以下一些技术栈和库:
- Django:用于后端管理和页面渲染。
- WebRTC:用于实时音视频传输。
- Django Channels:用于WebSocket通信。
以下是项目的基本结构和示例代码。
1. 设置Django项目
首先创建Django项目和应用:
sh
django-admin startproject livestream
cd livestream
django-admin startapp stream
2. 安装必要的依赖库
sh
pip install django channels channels_redis
3. 更新Django项目的设置
编辑 livestream/settings.py:
python
# settings.py
# 添加 Channels
INSTALLED_APPS = [
...,
'channels',
'stream', # 你的应用
]
# Channels 配置
ASGI_APPLICATION = 'livestream.asgi.application'
# Redis 配置
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
'hosts': [('127.0.0.1', 6379)],
},
},
}
# 模板路径
TEMPLATES = [
{
...
'DIRS': [BASE_DIR / 'templates'], # 若您在项目根目录下有一个 `templates` 文件夹
...
},
]
4. 配置 asgi.py
编辑 livestream/asgi.py:
python
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import stream.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'livestream.settings')
application = ProtocolTypeRouter(
{
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
stream.routing.websocket_urlpatterns
)
),
}
)
5. 创建路由
创建 stream/routing.py:
python
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/stream/$', consumers.StreamConsumer.as_asgi()),
]
6. 创建 Consumer
WebRTC的实际媒体传输是在浏览器完成的,Django只是处理信令部分。创建 stream/consumers.py:
python
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class StreamConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = 'stream'
self.room_group_name = 'stream_group'
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data):
data = json.loads(text_data)
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'stream_message',
'message': data,
}
)
async def stream_message(self, event):
message = event['message']
await self.send(text_data=json.dumps(message))
7. 创建视图和模板
编辑 stream/views.py:
python
from django.shortcuts import render
def index(request):
return render(request, 'stream/index.html')
创建 templates/stream/index.html:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebRTC Stream</title>
</head>
<body>
<h1>Live Stream</h1>
<video id="localVideo" autoplay></video>
<video id="remoteVideo" autoplay></video>
<script>
const localVideo = document.getElementById("localVideo");
const remoteVideo = document.getElementById("remoteVideo");
let localStream;
let remoteStream;
let peerConnection;
const ws = new WebSocket('ws://' + window.location.host + '/ws/stream/');
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(stream => {
localStream = stream;
localVideo.srcObject = stream;
peerConnection = new RTCPeerConnection();
localStream.getTracks().forEach(track => {
peerConnection.addTrack(track, localStream);
});
peerConnection.ontrack = event => {
if (!remoteVideo.srcObject) {
remoteStream = new MediaStream();
remoteVideo.srcObject = remoteStream;
}
remoteStream.addTrack(event.track);
};
peerConnection.onicecandidate = event => {
if (event.candidate) {
ws.send(JSON.stringify({
'candidate': event.candidate
}));
}
};
peerConnection.createOffer().then(offer => {
return peerConnection.setLocalDescription(offer);
}).then(() => {
ws.send(JSON.stringify({
'offer': peerConnection.localDescription
}));
});
});
ws.onmessage = function(e) {
const data = JSON.parse(e.data);
if (data.offer) {
peerConnection.setRemoteDescription(new RTCSessionDescription(data.offer)).then(() => {
return peerConnection.createAnswer();
}).then(answer => {
return peerConnection.setLocalDescription(answer);
}).then(() => {
ws.send(JSON.stringify({
'answer': peerConnection.localDescription
}));
});
} else if (data.answer) {
peerConnection.setRemoteDescription(new RTCSessionDescription(data.answer));
} else if (data.candidate) {
peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
}
};
</script>
</body>
</html>
8. 配置URL
编辑 stream/urls.py:
python
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
然后在 livestream/urls.py 中包含 stream 应用的路由:
python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('stream.urls')),
]
9. 启动服务器
确保Redis正在运行(可以用Docker运行 redis 容器),然后运行Django开发服务器:
sh
python manage.py runserver
总结
这是一个基本的Django与WebRTC结合的直播示例,实际操作中可能需要处理更多的细节和错误处理,如信令服务器更复杂的消息处理、ICE候选者的管理、连接中断处理等。为实际使用,还需要考虑各种边缘情况和优化。