Welcome to IPyWebRTC’s documentation!¶
WebRTC and MediaStream API exposed in the Jupyter notebook/lab.
See this tweet for a demo screencast.
- Using ipywebrtc you can create a MediaStream out of:
A video file.
An image file.
An audio file.
Your webcam/camera.
From this MediaStream you can:
Stream it to peers using the simple chat function.
Installation¶
Pip users:
$ pip install ipywebrtc # will auto enable for notebook >= 5.3
$ jupyter labextension install jupyter-webrtc # for jupyter lab
Conda users:
$ conda install -c conda-forge ipywebrtc
$ jupyter labextension install jupyter-webrtc # for jupyter lab
VideoStream¶
A VideoStream is a MediaStream from an attached video file or url.
[1]:
from ipywebrtc import VideoStream
Local file¶
You can create a video stream from a local file, note that the content of the file is embedded in the widget, meaning your notebook file can become quite large.
[2]:
# commented out since it increases the size of the notebook a lot
# video = VideoStream.from_file('./Big.Buck.Bunny.mp4')
# video
[3]:
# video
URL¶
A URL is also supported, but it must respect the same-origin policy (e.g. it must be hosted from the same server as the Javascript is executed from).
[4]:
# video2 = VideoStream.from_url('http://localhost:8888/path_to_your_hosted_file.mp4')
video2 = VideoStream.from_url('./Big.Buck.Bunny.mp4')
video2
In this example, video2 does not include the data of the video itself, only the url.
Download¶
For convenience, if a video is not same-origin, the below code will download it and put the content of the file in the widget (note again that the notebook will be large).
[5]:
# commented out since it increases the size of the notebook a lot
# video3 = VideoStream.from_download('https://webrtc.github.io/samples/src/video/chrome.webm')
# video3
Controlling¶
You can control a video for intance by linking a ToggleButton to a VideoStream:
[6]:
import ipywidgets as widgets
play_button = widgets.ToggleButton(description="Play")
widgets.jslink((play_button, 'value'), (video2, 'playing'))
widgets.VBox(children=[video2, play_button])
[ ]:
CameraStream¶
A CameraStream is a MediaStream from an attached camera device or webcam.
[1]:
from ipywebrtc import CameraStream, ImageRecorder
With constraints¶
You can pass constraints to the camera:
[2]:
camera = CameraStream(constraints=
{'facing_mode': 'user',
'audio': False,
'video': { 'width': 640, 'height': 480 }
})
camera
Front and back camera¶
Or use the two convenience methods:
[3]:
# this is a shorter way to get the user facing camera
front_camera = CameraStream.facing_user(audio=False)
# or the back facing camera
back_camera = CameraStream.facing_environment(audio=False)
[4]:
back_camera
Record images from the camera¶
[5]:
image_recorder = ImageRecorder(stream=camera)
image_recorder
[6]:
import PIL.Image
import PIL.ImageFilter
import io
im = PIL.Image.open(io.BytesIO(image_recorder.image.value))
---------------------------------------------------------------------------
UnidentifiedImageError Traceback (most recent call last)
<ipython-input-1-88478ab353f7> in <module>
2 import PIL.ImageFilter
3 import io
----> 4 im = PIL.Image.open(io.BytesIO(image_recorder.image.value))
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/PIL/Image.py in open(fp, mode, formats)
3022 warnings.warn(message)
3023 raise UnidentifiedImageError(
-> 3024 "cannot identify image file %r" % (filename if filename else fp)
3025 )
3026
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f9d18b37620>
[7]:
im.filter(PIL.ImageFilter.BLUR)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-886fedf7a729> in <module>
----> 1 im.filter(PIL.ImageFilter.BLUR)
NameError: name 'im' is not defined
[8]:
import numpy as np
im_array = np.array(im)
im_array
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-11fff624d0a1> in <module>
----> 1 import numpy as np
2 im_array = np.array(im)
3 im_array
ModuleNotFoundError: No module named 'numpy'
[ ]:
AudioStream¶
A AudioStream is similar to the VideoStream, but for audio only.
[1]:
from ipywebrtc import AudioStream
[2]:
audio = AudioStream.from_url('Big.Buck.Bunny.mp3')
audio
[3]:
audio.playing = False
[ ]:
WidgetStream¶
A WidgetStream creates a MediaStream out of any widget.
[1]:
from ipywebrtc import WidgetStream, VideoStream
Example with pythreejs: streaming of a webgl canvas¶
[2]:
from pythreejs import Mesh, SphereGeometry, MeshLambertMaterial, PerspectiveCamera, DirectionalLight, Scene, AmbientLight, Renderer, OrbitControls
ball = Mesh(
geometry=SphereGeometry(radius=1),
material=MeshLambertMaterial(color='red'),
position=[2, 1, 0]
)
c = PerspectiveCamera(
position=[0, 5, 5], up=[0, 1, 0],
children=[DirectionalLight(color='white', position=[3, 5, 1], intensity=0.5)]
)
scene = Scene(children=[ball, c, AmbientLight(color='#777777')])
renderer = Renderer(
camera=c,
scene=scene,
controls=[OrbitControls(controlling=c)]
)
renderer
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-68a83e58efcb> in <module>
----> 1 from pythreejs import Mesh, SphereGeometry, MeshLambertMaterial, PerspectiveCamera, DirectionalLight, Scene, AmbientLight, Renderer, OrbitControls
2 ball = Mesh(
3 geometry=SphereGeometry(radius=1),
4 material=MeshLambertMaterial(color='red'),
5 position=[2, 1, 0]
ModuleNotFoundError: No module named 'pythreejs'
[3]:
# the webgl_stream will be updated after the scene has changed (so drag the above ball around if nothing happens)
webgl_stream = WidgetStream(widget=renderer)
webgl_stream
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-cefdf25c17ba> in <module>
1 # the webgl_stream will be updated after the scene has changed (so drag the above ball around if nothing happens)
----> 2 webgl_stream = WidgetStream(widget=renderer)
3 webgl_stream
NameError: name 'renderer' is not defined
[4]:
# You can limit the fps
webgl_stream2 = WidgetStream(widget=renderer, max_fps=5)
webgl_stream2
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-ddf1e6b2bf7d> in <module>
1 # You can limit the fps
----> 2 webgl_stream2 = WidgetStream(widget=renderer, max_fps=5)
3 webgl_stream2
NameError: name 'renderer' is not defined
Example with ipywidgets: streaming of a slider widget¶
[5]:
from ipywidgets import FloatSlider
slider = FloatSlider(
value=7.5,
step=0.1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='.1f',
)
slider
[6]:
widget_stream = WidgetStream(widget=slider, max_fps=1)
widget_stream
[7]:
# Close the stream
widget_stream.close()
Example with ipyleaflet: streaming of a map widget¶
[8]:
from ipyleaflet import Map
m = Map(center=(46, 14), zoom=5)
m
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-ff582678bacf> in <module>
----> 1 from ipyleaflet import Map
2 m = Map(center=(46, 14), zoom=5)
3 m
ModuleNotFoundError: No module named 'ipyleaflet'
[9]:
map_stream = WidgetStream(widget=m, max_fps=1)
map_stream
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-fe4837077166> in <module>
----> 1 map_stream = WidgetStream(widget=m, max_fps=1)
2 map_stream
NameError: name 'm' is not defined
[10]:
map_stream.close()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-40e8f44f56da> in <module>
----> 1 map_stream.close()
NameError: name 'map_stream' is not defined
[ ]:
VideoRecorder¶
A VideoRecorder allows you to record any stream object, e.g. from:
[1]:
from ipywebrtc import VideoStream, VideoRecorder
[2]:
video = VideoStream.from_url('./Big.Buck.Bunny.mp4')
[3]:
video
[4]:
recorder = VideoRecorder(stream=video)
recorder
[5]:
video.playing = False
[6]:
recorder.video
Use ‘record’ button for recording. Programatical control is available using the MediaRecorder.record trait.
[7]:
recorder.recording = True
[8]:
recorder.recording = False
Saving can be done by clicking the download button, or programmatically using the save method. If autosave is True, the recording will be saved directly to disk.
[9]:
recorder.save('example.webm')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-1-3c2e0defaea1> in <module>
----> 1 recorder.save('example.webm')
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywebrtc/webrtc.py in save(self, filename)
451 filename += '.' + self.format
452 if len(self.video.value) == 0:
--> 453 raise ValueError('No data, did you record anything?')
454 with open(filename, 'wb') as f:
455 f.write(self.video.value)
ValueError: No data, did you record anything?
[10]:
from ipywidgets import Video
example = Video.from_file('example.webm')
example
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-1-b7367ffe4f50> in <module>
1 from ipywidgets import Video
2
----> 3 example = Video.from_file('example.webm')
4 example
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywidgets/widgets/widget_media.py in from_file(cls, filename, **kwargs)
192 @classmethod
193 def from_file(cls, filename, **kwargs):
--> 194 return cls._from_file('video', filename, **kwargs)
195
196 def __repr__(self):
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywidgets/widgets/widget_media.py in _from_file(cls, tag, filename, **kwargs)
42 Returns an `Media` with the value set from the filename.
43 """
---> 44 value = cls._load_file_value(filename)
45
46 if 'format' not in kwargs:
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywidgets/widgets/widget_media.py in _load_file_value(cls, filename)
93 return filename.read()
94 else:
---> 95 with open(filename, 'rb') as f:
96 return f.read()
97
FileNotFoundError: [Errno 2] No such file or directory: 'example.webm'
ImageRecorder¶
A ImageRecorder allows you to record a screenshot from any stream object, e.g. from:
[1]:
import ipywidgets as widgets
from ipywebrtc import ImageRecorder, VideoStream
[2]:
video = VideoStream.from_url('Big.Buck.Bunny.mp4')
video
Using the image recorder, you can take screenshot of the stream clicking the camera button
[3]:
image_recorder = ImageRecorder(stream=video)
image_recorder
[4]:
image_recorder.image
Or do it, programatically:
[5]:
image_recorder.recording = True
[6]:
image_recorder.autosave = False
[7]:
image_recorder.download()
[8]:
image_recorder.image.height
[8]:
''
The data is PNG encoded (by default), so we show how to use PIL to read in the data
[9]:
import PIL.Image
import PIL.ImageFilter
import io
im = PIL.Image.open(io.BytesIO(image_recorder.image.value))
---------------------------------------------------------------------------
UnidentifiedImageError Traceback (most recent call last)
<ipython-input-1-88478ab353f7> in <module>
2 import PIL.ImageFilter
3 import io
----> 4 im = PIL.Image.open(io.BytesIO(image_recorder.image.value))
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/PIL/Image.py in open(fp, mode, formats)
3022 warnings.warn(message)
3023 raise UnidentifiedImageError(
-> 3024 "cannot identify image file %r" % (filename if filename else fp)
3025 )
3026
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f920018c518>
PIL Images display by default as image in the notebook. Calling the filter methods returns a new image which gets displayed directly.
[10]:
im.filter(PIL.ImageFilter.BLUR)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-886fedf7a729> in <module>
----> 1 im.filter(PIL.ImageFilter.BLUR)
NameError: name 'im' is not defined
Example with scikit image¶
We first convert the png encoded data to raw pixel values (as a numpy array).
[11]:
import numpy as np
im_array = np.array(im)
im_array
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-11fff624d0a1> in <module>
----> 1 import numpy as np
2 im_array = np.array(im)
3 im_array
ModuleNotFoundError: No module named 'numpy'
Now we can do easy manipulatios, such as reordering the channels (red, green, blue, alpha)
[12]:
PIL.Image.fromarray(im_array[...,::-1])
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-b8ec24da4056> in <module>
----> 1 PIL.Image.fromarray(im_array[...,::-1])
NameError: name 'im_array' is not defined
Or build a slightly more sophisticated example using scikit-image (run this notebook with a live kernel, such as mybinder for this to work)
[13]:
from skimage.filters import roberts, sobel, scharr, prewitt
from skimage.color import rgb2gray
from skimage.color.adapt_rgb import adapt_rgb, each_channel, hsv_value
from skimage import filters
image = widgets.Image()
output = widgets.Output()
filter_options = [('roberts', roberts), ('sobel', sobel), ('scharr', scharr), ('prewitt', prewitt)]
filter_widget = widgets.ToggleButtons(options=filter_options)
@output.capture()
def update_image(change):
# turn into nparray
im_in = PIL.Image.open(io.BytesIO(image_recorder.image.value))
im_array = np.array(im_in)[...,:3] # no alpha
# filter
filter_function = filter_widget.value
im_array_edges = adapt_rgb(each_channel)(filter_function)(im_array)
im_array_edges = ((1-im_array_edges) * 255).astype(np.uint8)
im_out = PIL.Image.fromarray(im_array_edges)
# store in image widget
f = io.BytesIO()
im_out.save(f, format='png')
image.value = f.getvalue()
image_recorder.image.observe(update_image, 'value')
filter_widget.observe(update_image, 'value')
widgets.VBox([filter_widget, video, widgets.HBox([image_recorder, image]), output])
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-7d48ae9c1545> in <module>
----> 1 from skimage.filters import roberts, sobel, scharr, prewitt
2 from skimage.color import rgb2gray
3 from skimage.color.adapt_rgb import adapt_rgb, each_channel, hsv_value
4 from skimage import filters
5
ModuleNotFoundError: No module named 'skimage'
[ ]:
AudioRecorder¶
A AudioRecorder allows you to record audio from almost any stream object, e.g. from:
[1]:
from ipywebrtc import VideoStream, AudioStream, AudioRecorder
[2]:
video = VideoStream.from_url('./Big.Buck.Bunny.mp4')
video
[3]:
recorder = AudioRecorder(stream=video)
recorder
[4]:
video.playing = False
[5]:
recorder.audio
[6]:
recorder.save('example.webm')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-1-3c2e0defaea1> in <module>
----> 1 recorder.save('example.webm')
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywebrtc/webrtc.py in save(self, filename)
509 filename += '.' + self.format
510 if len(self.audio.value) == 0:
--> 511 raise ValueError('No data, did you record anything?')
512 with open(filename, 'wb') as f:
513 f.write(self.audio.value)
ValueError: No data, did you record anything?
[7]:
from ipywidgets import Audio
example = Audio.from_file('example.webm')
example
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-1-ac3650e27fbd> in <module>
1 from ipywidgets import Audio
2
----> 3 example = Audio.from_file('example.webm')
4 example
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywidgets/widgets/widget_media.py in from_file(cls, filename, **kwargs)
221 @classmethod
222 def from_file(cls, filename, **kwargs):
--> 223 return cls._from_file('audio', filename, **kwargs)
224
225 def __repr__(self):
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywidgets/widgets/widget_media.py in _from_file(cls, tag, filename, **kwargs)
42 Returns an `Media` with the value set from the filename.
43 """
---> 44 value = cls._load_file_value(filename)
45
46 if 'format' not in kwargs:
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywidgets/widgets/widget_media.py in _load_file_value(cls, filename)
93 return filename.read()
94 else:
---> 95 with open(filename, 'rb') as f:
96 return f.read()
97
FileNotFoundError: [Errno 2] No such file or directory: 'example.webm'
[8]:
audio_stream = AudioStream.from_file('example.webm')
audio_stream
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-1-8a5a850a98be> in <module>
----> 1 audio_stream = AudioStream.from_file('example.webm')
2 audio_stream
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywebrtc/webrtc.py in from_file(cls, filename, **kwargs)
214 Extra keyword arguments for `AudioStream`
215 """
--> 216 audio = Audio.from_file(filename, autoplay=False, controls=False)
217 return cls(audio=audio, **kwargs)
218
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywidgets/widgets/widget_media.py in from_file(cls, filename, **kwargs)
221 @classmethod
222 def from_file(cls, filename, **kwargs):
--> 223 return cls._from_file('audio', filename, **kwargs)
224
225 def __repr__(self):
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywidgets/widgets/widget_media.py in _from_file(cls, tag, filename, **kwargs)
42 Returns an `Media` with the value set from the filename.
43 """
---> 44 value = cls._load_file_value(filename)
45
46 if 'format' not in kwargs:
~/checkouts/readthedocs.org/user_builds/ipywebrtc/conda/latest/lib/python3.6/site-packages/ipywidgets/widgets/widget_media.py in _load_file_value(cls, filename)
93 return filename.read()
94 else:
---> 95 with open(filename, 'rb') as f:
96 return f.read()
97
FileNotFoundError: [Errno 2] No such file or directory: 'example.webm'
[9]:
recorder2 = AudioRecorder(stream=audio_stream)
recorder2
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-fd38b7a59177> in <module>
----> 1 recorder2 = AudioRecorder(stream=audio_stream)
2 recorder2
NameError: name 'audio_stream' is not defined
[10]:
audio_stream.playing = False
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-b580674f95d1> in <module>
----> 1 audio_stream.playing = False
NameError: name 'audio_stream' is not defined
API docs¶
Note that ipywebrtc.webrtc
is imported in the ipywebrtc namespace, to you can access ipywebrtc.CameraStream instead of ipywebrtc.webrtc.CameraStream
.
ipywebrtc¶
- ipywebrtc.chat(room=None, stream=None, **kwargs)[source]¶
Quick setup for a chatroom.
- Parameters
room (str) – Roomname, if not given, a random sequence is generated and printed.
stream (MediaStream) – The media stream to share, if not given a CameraStream will be created.
- Return type
ipywebrtc.webrtc¶
- class ipywebrtc.webrtc.AudioRecorder(*args, **kwargs)[source]¶
Bases:
Recorder
Creates a recorder which allows to record the Audio of a MediaStream widget, play the record in the Notebook, and download it or turn it into an Audio widget.
For help on supported values for the “codecs” attribute, see https://stackoverflow.com/questions/41739837/all-mime-types-supported-by-mediarecorder-in-firefox-and-chrome
- audio¶
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
Subclasses can declare default classes by overriding the klass attribute
- codecs¶
Optional codecs for the recording, e.g. “opus”.
- save(filename=None)[source]¶
Save the audio to a file, if no filename is given it is based on the filename trait and the format.
>>> recorder = AudioRecorder(filename='test', format='mp3') >>> ... >>> recorder.save() # will save to test.mp3 >>> recorder.save('foo') # will save to foo.mp3 >>> recorder.save('foo.dat') # will save to foo.dat
- class ipywebrtc.webrtc.AudioStream(*args, **kwargs)[source]¶
Bases:
MediaStream
Represent a stream of an audio element
- audio¶
An ipywidgets.Audio instance that will be the source of the media stream.
- classmethod from_download(url, **kwargs)[source]¶
Create a AudioStream from a url by downloading
- Parameters
url (str) – The url of the file that will be downloadeded and its bytes assigned to the value trait of the video trait.
**kwargs – Extra keyword arguments for AudioStream
- classmethod from_file(filename, **kwargs)[source]¶
Create a AudioStream from a local file.
- Parameters
filename (str) – The location of a file to read into the audio value from disk.
**kwargs – Extra keyword arguments for AudioStream
- classmethod from_url(url, **kwargs)[source]¶
Create a AudioStream from a url.
This will create a AudioStream from an Audio using its url
- Parameters
url (str) – The url of the file that will be used for the .audio trait.
**kwargs – Extra keyword arguments for AudioStream
- playing¶
Plays the audiostream or pauses it.
- class ipywebrtc.webrtc.CameraStream(*args, **kwargs)[source]¶
Bases:
MediaStream
Represents a media source by a camera/webcam/microphone using getUserMedia. See https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia for more detail. The constraints trait can be set to specify constraints for the camera or microphone, which is described in the documentation of getUserMedia, such as in the link above, Two convenience methods are avaiable to easily get access to the ‘front’ and ‘back’ camera, when present
>>> CameraStream.facing_user(audio=False) >>> CameraStream.facing_environment(audio=False)
- constraints¶
//developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia for details.
- Type
Constraints for the camera, see https
- class ipywebrtc.webrtc.ImageRecorder(*args, **kwargs)[source]¶
Bases:
Recorder
Creates a recorder which allows to grab an Image from a MediaStream widget.
- format¶
The format of the image.
- image¶
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
Subclasses can declare default classes by overriding the klass attribute
- save(filename=None)[source]¶
Save the image to a file, if no filename is given it is based on the filename trait and the format.
>>> recorder = ImageRecorder(filename='test', format='png') >>> ... >>> recorder.save() # will save to test.png >>> recorder.save('foo') # will save to foo.png >>> recorder.save('foo.dat') # will save to foo.dat
- class ipywebrtc.webrtc.ImageStream(*args, **kwargs)[source]¶
Bases:
MediaStream
Represent a media stream by a static image
- classmethod from_download(url, **kwargs)[source]¶
Create a ImageStream from a url by downloading
- Parameters
url (str) – The url of the file that will be downloadeded and its bytes assigned to the value trait of the video trait.
**kwargs – Extra keyword arguments for ImageStream
- classmethod from_file(filename, **kwargs)[source]¶
Create a ImageStream from a local file.
- Parameters
filename (str) – The location of a file to read into the value from disk.
**kwargs – Extra keyword arguments for ImageStream
- classmethod from_url(url, **kwargs)[source]¶
Create a ImageStream from a url.
This will create a ImageStream from an Image using its url
- Parameters
url (str) – The url of the file that will be used for the .image trait.
**kwargs – Extra keyword arguments for ImageStream
- image¶
An ipywidgets.Image instance that will be the source of the media stream.
- class ipywebrtc.webrtc.MediaStream(*args, **kwargs)[source]¶
Bases:
DOMWidget
Represents a media source.
See https://developer.mozilla.org/nl/docs/Web/API/MediaStream for details In practice this can a stream coming from an HTMLVideoElement, HTMLCanvasElement (could be a WebGL canvas) or a camera/webcam/microphone using getUserMedia.
- The currently supported MediaStream (subclasses) are:
VideoStream
: A video file/data as media stream.CameraStream
: Webcam/camera as media stream.ImageStream
: An image as a static stream.WidgetStream
: Arbitrary DOMWidget as stream.
- A MediaStream can be used with:
VideoRecorder
: To record a movieImageRecorder
: To create images/snapshots.AudioRecorder
: To record audio.WebRTCRoom
(or ratherWebRTCRoomMqtt
): To stream a media stream to a (set of) peers.
- class ipywebrtc.webrtc.Recorder(*args, **kwargs)[source]¶
Bases:
DOMWidget
- autosave¶
If true, will save the data to a file once the recording is finished (based on filename and format)
- filename¶
The filename used for downloading or auto saving.
- format¶
The format of the recording.
- recording¶
(boolean) Indicator and controller of the recorder state, i.e. putting the value to True will start recording.
- stream¶
An instance of
MediaStream
that is the source for recording.
- class ipywebrtc.webrtc.VideoRecorder(*args, **kwargs)[source]¶
Bases:
Recorder
Creates a recorder which allows to record a MediaStream widget, play the record in the Notebook, and download it or turn it into a Video widget.
For help on supported values for the “codecs” attribute, see https://stackoverflow.com/questions/41739837/all-mime-types-supported-by-mediarecorder-in-firefox-and-chrome
- codecs¶
Optional codecs for the recording, e.g. “vp8” or “vp9, opus”.
- save(filename=None)[source]¶
Save the video to a file, if no filename is given it is based on the filename trait and the format.
>>> recorder = VideoRecorder(filename='test', format='mp4') >>> ... >>> recorder.save() # will save to test.mp4 >>> recorder.save('foo') # will save to foo.mp4 >>> recorder.save('foo.dat') # will save to foo.dat
- video¶
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
Subclasses can declare default classes by overriding the klass attribute
- class ipywebrtc.webrtc.VideoStream(*args, **kwargs)[source]¶
Bases:
MediaStream
Represent a stream of a video element
- classmethod from_download(url, **kwargs)[source]¶
Create a VideoStream from a url by downloading
- Parameters
url (str) – The url of the file that will be downloadeded and its bytes assigned to the value trait of the video trait.
**kwargs – Extra keyword arguments for VideoStream
- classmethod from_file(filename, **kwargs)[source]¶
Create a VideoStream from a local file.
- Parameters
filename (str) – The location of a file to read into the value from disk.
**kwargs – Extra keyword arguments for VideoStream
- classmethod from_url(url, **kwargs)[source]¶
Create a VideoStream from a url.
This will create a VideoStream from a Video using its url
- Parameters
url (str) – The url of the file that will be used for the .video trait.
**kwargs – Extra keyword arguments for VideoStream
- playing¶
Plays the videostream or pauses it.
- video¶
An ipywidgets.Video instance that will be the source of the media stream.
- class ipywebrtc.webrtc.WebRTCPeer(*args, **kwargs)[source]¶
Bases:
DOMWidget
A peer-to-peer webrtc connection
- connected¶
A boolean (True, False) trait.
- failed¶
A boolean (True, False) trait.
- id_local¶
A trait for unicode strings.
- id_remote¶
A trait for unicode strings.
- stream_local¶
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
Subclasses can declare default classes by overriding the klass attribute
- stream_remote¶
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
Subclasses can declare default classes by overriding the klass attribute
- class ipywebrtc.webrtc.WebRTCRoom(*args, **kwargs)[source]¶
Bases:
DOMWidget
A ‘chatroom’, which consists of a list of :WebRTCPeer connections
- nickname¶
A trait for unicode strings.
- peers¶
An instance of a Python list.
- room¶
A trait for unicode strings.
- room_id¶
A trait for unicode strings.
- stream¶
A trait whose value must be an instance of a specified class.
The value can also be an instance of a subclass of the specified class.
Subclasses can declare default classes by overriding the klass attribute
- streams¶
An instance of a Python list.
- class ipywebrtc.webrtc.WebRTCRoomLocal(*args, **kwargs)[source]¶
Bases:
WebRTCRoom
- class ipywebrtc.webrtc.WebRTCRoomMqtt(*args, **kwargs)[source]¶
Bases:
WebRTCRoom
Use a mqtt server to connect to other peers
- server¶
A trait for unicode strings.
- class ipywebrtc.webrtc.WidgetStream(*args, **kwargs)[source]¶
Bases:
MediaStream
Represents a widget media source.
- max_fps¶
(int, default None) The maximum amount of frames per second to capture, or only on new data when the valeus is None.
- widget¶
An instance of ipywidgets.DOMWidget that will be the source of the MediaStream.
Demos¶
WebRTC and ipyvolume¶
Use remote MediaStreams and show them in 3d using ipyvolume.

webrtc¶
ImageRecorder¶
Record and image from any stream for postprocessing.

recorder¶
WidgetStream¶
Turn any widget into a MediaStream.

widget-stream¶