use a multimedia player to play a stream
506727
def play(self, name, streamUrl, encoding = ''):
        
        self.close()
        self.name = name
        self.oldUserInput = {'Input': '', 'Volume': '', 'Title': ''}
        self.muted = False
        self.show_volume = True
        self.title_prefix = ''
        self.playback_is_on = False
        self.outputStream.write('Station: "{}"'.format(name), self.status_update_lock)
        if logger.isEnabledFor(logging.INFO):
            logger.info('Selected Station: "{}"'.format(name))
        if encoding:
            self._station_encoding = encoding
        else:
            self._station_encoding = 'utf-8'
        opts = []
        isPlayList = streamUrl.split("?")[0][-3:] in ['m3u', 'pls']
        opts = self._buildStartOpts(streamUrl, isPlayList)
        self.process = subprocess.Popen(opts, shell=False,
                                        stdout=subprocess.PIPE,
                                        stdin=subprocess.PIPE,
                                        stderr=subprocess.STDOUT)
        t = threading.Thread(target=self.updateStatus, args=(self.status_update_lock, ))
        t.start()
        # start playback check timer thread
        try:
            self.connection_timeout_thread = threading.Timer(self.playback_timeout, self.playback_timeout_handler)
            self.connection_timeout_thread.start()
        except:
            self.connection_timeout_thread = None
            if (logger.isEnabledFor(logging.ERROR)):
                logger.error("playback detection thread start failed")
        if logger.isEnabledFor(logging.INFO):
            logger.info("Player started")
514481
def run(self):
    
    # From now on, it's multi-thread. Let the force be with them.
    st = self.stream._stream

    for chunk in chunks(self.audio,
                        size=self.chunk_size*self.nchannels,
                        dfmt=self.dfmt):
      #Below is a faster way to call:
      #  self.stream.write(chunk, self.chunk_size)
      self.write_stream(st, chunk, self.chunk_size, False)
      if not self.go.is_set():
        self.stream.stop_stream()
        if self.halting:
          break
        self.go.wait()
        self.stream.start_stream()

    # Finished playing! Destructor-like step: let's close the thread
    with self.lock:
      if self in self.device_manager._threads: # If not already closed
        self.stream.close()
        self.device_manager.thread_finished(self)
505242
async def vafter(self):
        """"""
        self.logger.debug("Finished playing a song")
        if self.state != 'ready':
            self.logger.debug("Returning because player is in state {}".format(self.state))
            return

        self.pause_time = None

        if self.vclient_task:
            loop = asyncio.get_event_loop()
            loop.call_soon(self.vclient_task.cancel)
            self.vclient_task = None

        try:
            if self.streamer is None:
                await self.stop()
                return

            if self.streamer.error is None:
                await self.vplay()
            else:
                self.statuslog.error(self.streamer.error)
                await self.destroy()
        except Exception as e:
            logger.exception(e)
            try:
                await self.destroy()
            except Exception as e:
                logger.exception(e)
262111
async def recv(self):
        
        if self.readyState != 'live':
            raise MediaStreamError

        frame = await self._queue.get()
        if frame is None:
            self.stop()
            raise MediaStreamError
        return frame
1217922
public void stream(InputStream inputStream, MediaType mediaType) {
        try {
            OutputStream outputStream = exchange.getOutputStream();
            setResponseMediaType(mediaType);

            byte[] buffer = new byte[10240];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception ex) {
            throw new RuntimeException("Error transferring data", ex);
        }
    }
736643
protected void nativePlay(Element video) {
        MediaStream stream = null;
        if (Navigator.getUserMedia != null) {
            stream = Navigator.getUserMedia;
            GWT.log("Uses Default user Media");
        } else if (Navigator.webkitGetUserMedia != null) {
            stream = Navigator.webkitGetUserMedia;
            GWT.log("Uses Webkit User Media");
        } else if (Navigator.mozGetUserMedia != null) {
            stream = Navigator.mozGetUserMedia;
            GWT.log("Uses Moz User Media");
        } else if (Navigator.msGetUserMedia != null) {
            stream = Navigator.msGetUserMedia;
            GWT.log("Uses Microsoft user Media");
        } else {
            GWT.log("No supported media found in your browser");
        }

        if (stream != null) {
            Navigator.getMedia = stream;
            Constraints constraints = new Constraints();
            constraints.audio = false;

            MediaTrackConstraints mediaTrackConstraints = new MediaTrackConstraints();
            mediaTrackConstraints.width = width;
            mediaTrackConstraints.height = height;
            mediaTrackConstraints.facingMode = facingMode.getName();
            constraints.video = mediaTrackConstraints;

            Navigator.mediaDevices.getUserMedia(constraints).then(streamObj -> {
                mediaStream = (MediaStream) streamObj;
                if (URL.createObjectURL(mediaStream) != null) {
                    $(video).attr("src", URL.createObjectURL(mediaStream));
                } else if (WebkitURL.createObjectURL(mediaStream) != null) {
                    $(video).attr("src", WebkitURL.createObjectURL(mediaStream));
                }
                if (video instanceof VideoElement) {
                    ((VideoElement) video).play();
                }
                onCameraCaptureLoad();
                return null;
            }).catchException(error -> {
                GWT.log("MaterialCameraCapture: An error occured! " + error);
                onCameraCaptureError(error.toString());
                return null;
            });
        }
    }
974623
def play_async(cls, file_path, on_done=None):
        
        thread = threading.Thread(
            target=AudioPlayer.play, args=(file_path, on_done,))
        thread.start()
1147002
@Override
    public void play(final String uri) {
        Log.d(TAG, "Start playing "+uri);
        notifyVideoUnavailable(REASON_BUFFERING);
        isWeb = false;
        TvInputPlayer.Callback callback = new TvInputPlayer.Callback() {
            @Override
            public void onPrepared() {
                notifyVideoAvailable();
                setOverlayEnabled(false);
            }

            @Override
            public void onPlayerStateChanged(boolean playWhenReady, int state) {

            }

            @Override
            public void onPlayWhenReadyCommitted() {

            }

            @Override
            public void onPlayerError(ExoPlaybackException e) {
                Log.e(TAG, e.getMessage()+"");
                if(e.getMessage().contains("Extractor")) {
                    Log.d(TAG, "Cannot play the stream, try loading it as a website");
                    Log.d(TAG, "Open "+uri);
                    //Pretend this is a website
                    loadUrl(uri);
                    isWeb = true;
                    setOverlayEnabled(false);
                    notifyVideoAvailable();
                    isWeb = true;
                    setOverlayEnabled(false);
                    setOverlayEnabled(true);
                    isWeb = true;
                }
            }

            @Override
            public void onDrawnToSurface(Surface surface) {

            }

            @Override
            public void onText(String text) {

            }
        };
        try {
            tvInputPlayer.removeCallback(callback);
        } catch(NullPointerException e) {
            Log.w(TAG, "exoplayer.removeCallback error "+e.getMessage());
        }
        tvInputPlayer.addCallback(callback);
        tvInputPlayer.setSurface(mSurface);
        Log.d(TAG, "Play "+uri+"; "+uri.indexOf("file:///"));
        if(uri.contains("file:///")) {
            Log.i(TAG, "Is a local file");
            //Find appropriate extractor

            DataSource dataSource=new DefaultUriDataSource(getApplicationContext(), TvInputPlayer.getUserAgent(getApplicationContext()));
            ExtractorSampleSource extractorSampleSource=new ExtractorSampleSource(Uri.parse(uri),dataSource,
                    new DefaultAllocator(TvInputPlayer.BUFFER_SEGMENT_SIZE), TvInputPlayer.BUFFER_SEGMENTS * TvInputPlayer.BUFFER_SEGMENT_SIZE,
                    new Mp4Extractor(), new Mp3Extractor());
            TrackRenderer audio=new MediaCodecAudioTrackRenderer(extractorSampleSource, MediaCodecSelector.DEFAULT);
            TrackRenderer video=new MediaCodecVideoTrackRenderer(getApplicationContext(),extractorSampleSource, MediaCodecSelector.DEFAULT, MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
            tvInputPlayer.prepare(audio, video, new DummyTrackRenderer());
        } else {
            try {
                tvInputPlayer.prepare(getApplicationContext(), Uri.parse(uri), TvInputPlayer.SOURCE_TYPE_HLS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        tvInputPlayer.setPlayWhenReady(true);
    }
143815
def play():
    """"""
    with sqlite3.connect(ARGS.database) as connection:
        connection.text_factory = str
        cursor = connection.cursor()
        if ARGS.pattern:
            if not ARGS.strict:
                ARGS.pattern = '%{0}%'.format(ARGS.pattern)
            cursor.execute('SELECT * FROM Movies WHERE Name LIKE (?)',
                           [ARGS.pattern])
            try:
                path = sorted([row for row in cursor])[0][1]
                replace_map = {' ': '\\ ', '"': '\\"', "'": "\\'"}
                for key, val in replace_map.iteritems():
                    path = path.replace(key, val)
                os.system('{0} {1} &'.format(ARGS.player, path))
            except IndexError:
                exit('Error: Movie not found.')
310232
def libvlc_media_player_set_media(p_mi, p_md):
    '''
    '''
    f = _Cfunctions.get('libvlc_media_player_set_media', None) or \
        _Cfunction('libvlc_media_player_set_media', ((1,), (1,),), None,
                    None, MediaPlayer, Media)
    return f(p_mi, p_md)
615246
async def create_ffmpeg_player(self, filepath):
        """"""
        self.current_download_elapsed = 0

        self.streamer = self.vclient.create_ffmpeg_player(filepath, after=self.vafter_ts)
        self.state = "ready"
        await self.setup_streamer()

        try:
            # Read from the info json
            info_filename = "{}.info.json".format(filepath)
            with open(info_filename, 'r') as file:
                info = json.load(file)

                self.nowplayinglog.debug(info["title"])
                self.is_live = False

                if "duration" in info and info["duration"] is not None:
                    self.current_duration = info["duration"]
                else:
                    self.current_duration = 0

                if "uploader" in info:
                    self.nowplayingauthorlog.info(info["uploader"])
                else:
                    self.nowplayingauthorlog.info("Unknown")

                self.nowplayingsourcelog.info(api_music.parse_source(info))

                play_state = "Streaming" if self.is_live else "Playing"
                await self.set_topic("{} {}".format(play_state, info["title"]))
                self.statuslog.debug(play_state)
        except Exception as e:
            logger.exception(e)
1324673
function listen (stream_url, options, callback) {
    if (options && options.constructor===Function) {
        callback = options;
        options = undefined;
    }
    var u = url.parse(stream_url.toString());
    var proto = u.protocol.substr(0, u.protocol.length-1);
    var adaptor = adaptors[proto];
    if (!adaptor) {
        throw new Error('protocol unknown: '+u.protocol);
    }
    return adaptor.listen(u, options, callback);
}
846711
def play(quiet, session_file, shell, speed, prompt, commentecho):
    """"""
    run(
        session_file.readlines(),
        shell=shell,
        speed=speed,
        quiet=quiet,
        test_mode=TESTING,
        prompt_template=prompt,
        commentecho=commentecho,
    )
653155
def realtime_stream(self, channel=1, typeno=0, path_file=None):
        
        ret = self.command(
            'realmonitor.cgi?action=getStream&channel={0}&subtype={1}'.format(
                channel, typeno)
        )

        if path_file:
            with open(path_file, 'wb') as out_file:
                shutil.copyfileobj(ret.raw, out_file)

        return ret.raw
303227
def libvlc_media_player_get_media(p_mi):
    '''
    '''
    f = _Cfunctions.get('libvlc_media_player_get_media', None) or \
        _Cfunction('libvlc_media_player_get_media', ((1,),), class_result(Media),
                    ctypes.c_void_p, MediaPlayer)
    return f(p_mi)
612904
def play(self):
		
		# Signal player to start video playback
		self.paused = False

		# Start listening for incoming audio frames
		if self.decoder.audioformat:
			self.audio.start()

		self.decoder.play()

		# While video is playing, render frames
		while self.decoder.status in [mediadecoder.PLAYING, mediadecoder.PAUSED]:
			texture_update_time = 0
			if self.texUpdated:
				t1 = time.time()
				# Update texture
				self.texture_locked = True
				glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, self.vidsize[0], 
					self.vidsize[1], GL_RGB, GL_UNSIGNED_BYTE, self.buffer)
				self.texture_locked = False
				texture_update_time = int((time.time()-t1)*1000)
				self.texUpdated = False
			
			# Draw the texture to the back buffer
			t1 = time.time()
			self.__drawFrame()
			draw_time = (time.time()-t1)*1000
			# Flip the buffer to show frame to screen
			t1 = time.time()
			pygame.display.flip()
			flip_time = (time.time()-t1)*1000

			logger.debug("================== Frame {} ========================"
				"".format(self.decoder.current_frame_no))
			if texture_update_time:
				logger.debug("Texture updated in {0} ms".format(texture_update_time))
			logger.debug("Texture drawn in {0} ms".format(draw_time))
			logger.debug("Screen flipped in {0} ms".format(flip_time))
			logger.debug("-----------------------------------------------------")
			logger.debug("Total: {} ms".format(texture_update_time+draw_time+flip_time))

			for e in pygame.event.get():
				if e.type == pygame.QUIT:
					self.stop()
				if e.type == pygame.KEYDOWN:
					# Quitting
					if e.key == pygame.K_ESCAPE:
						self.stop()
					# Pausing
					elif e.key == pygame.K_SPACE:
						self.pause()
					# Seeking
					elif e.key == pygame.K_RIGHT:
						new_time = min(
							self.decoder.current_playtime + 10,
							self.decoder.duration)
						self.decoder.seek(new_time)
					elif e.key == pygame.K_LEFT:
						new_time = max(
							self.decoder.current_playtime - 10,
							0)
						self.decoder.seek(new_time)

			pygame.event.pump()   # Prevent freezing of screen while dragging 

			# Without this sleep, the video rendering threard goes haywire...
			time.sleep(0.005)
		
		if self.decoder.audioformat:
			self.audio.close_stream()
				
		pygame.quit()
494662
public void play(boolean loop) throws IOException {
		this.loop = loop;
		initStreams();
		
		done = false;

		AL10.alSourceStop(source);
		removeBuffers();
		
		startPlayback();
	}