Notreadableerror could not start video source ошибка

Как исправить ошибку «Notreadableerror: could not start video source» в javascript

Эта ошибка появляется когда вы вызываете getUsermedia, обычно на мобильных телефонах. Причиной обычно является то что вы не правильно «выключаете» вашу камеру перед послеующими действиями над ней. Например у меня ошибка появлялась когда я создал функцию смены камеры с фронтальной на пользовательскую. 

Чтобы решить эту проблему вам нужно перед последующими вызовами getUserMedia «закрывать» камеру. Делается это так:

mediastream.getTracks().forEach(track => track.stop())

В переменной mediastream должен быть результат предыдущего вызова getUserMedia. После  этого вы можете запустить getUserMedia заного, с новыми параметрами которые вы хотите задать итд.

Вот как я решил эту задачу через VueJS:

<template>
  <div>
    <div>
      <button @click="rotateCamera">Rotate</button>
    </div>
    <video ref="cameraPicture" :srcObject.prop="mediastream" autoplay muted></video>
    <record-button ref="record" @start-recording="startRecording" @stop-recording="stopRecording" v-if="mediastream"/>
  </div>
</template>
<script>
import Vue from "vue";
import recordButton from "./RecordButton"
export default Vue.component('record-screen', {
  data() {
    return {
      mediastream: "",
      front: false,
    };
  },
  methods: {
    rotateCamera: function() {
      this.front = !this.front;
    },
    updateMedia: function(){
      var constraints = { audio: true, video: { facingMode: (this.front? "user" : "environment") } };
      navigator.mediaDevices.getUserMedia(constraints)
        .then((mediaStream) => {
            this.mediastream = mediaStream
            this.mediaRecorder = new MediaRecorder(mediaStream, {mimeType : 'video/webm;codecs=h264'});
            this.mediaRecorder.ondataavailable = (blob) => {
              this.$emit('setParentState', 'recorded_video', blob.data)
              this.$emit('nextStage')
            }
        })
    },
    startRecording: function(){
      this.mediaRecorder.start()
    },
    stopRecording: function(){
      this.mediaRecorder.stop()
    }
  },
  mounted(){
    this.updateMedia()
  },
  watch: {
    front: function () {
      this.mediastream.getTracks().forEach(track => track.stop());
      this.updateMedia()
    },
  }
});
</script>

Популярные сообщения из этого блога

DOS атака при помощи Python

Изображение

Для атак вида «DOS» используют один мощный сервер который посылает жертве столько запросов, что жертва не успевает обработать их и выдаёт ошибку 503 либо 504. Для атаки нужна многопоточность, то есть нужно чтобы скрипт отправлял запрос не ожидая завершения предыдущего. В Python для этого есть библиотека «therading». Пример простейшего скрипта для доса: # coding: utf8 import threading import requests def dos (): while True : requests . get( «http://example.com» ) while True : threading . Thread(target = dos) . start() Скрипт рекомендую запускать только на мощных компьютерах а ещё лучше на VPS сервере. Вот наш скрипт в действии: Так же советую попробовать новый ддос скрипт который использует вместо потоков асинхронный код

Ведем телеграм канал через питон

Изображение

Для создания ботов существует библиотека  aiogram . Но не всегда обязательно использовать ботов, вить иногда вам просто нужно посылать сообщения в канал с собственного имени. Для этого больше всего подходит библиотека  pyrogram . Устанавливаем её: pip install pyrogram Далее нужно создать телеграм приложение, от которого будут посылатся запросы. Создать приложение можно на  https://my.telegram.org/apps . После регистрации приложения должна появится такая форма: Как посылать сообщения в канал  from  pyrogram  import  Client api_id =  12345 api_hash =  «0123456789abcdef0123456789abcdef» with  Client( «my_account» , api_id, api_hash)  as  app:     app.send_message( «me» ,  «Greetings from **Pyrogram**!» ) Вместо api_id и api_hash нужно подставить свои данные, полученные при регистрации. Далее нужно ввести свой номер телефона, и ввести код который пришел на него. В этой же директории будет файл  my_account.session . В нем содержится сама сейсия. В сох

Django migrations не видит изменения моделей

Изображение

В некоторых случаях python manage.py makemigrations может выдавать сообщение No changes detected: Если у вас на самом деле были изменения в моделях, но Django не видит изменений это свидетельстует о проблеме. В моих случаях решения были такие: Приложения нету в INSTALLED_APPS Если вы не добавили свое приложения в него, то Django неможет видеть ваши модели. Нарушена структура приложения Иногда вам хочется удалить папку migrations, чтобы с нуля создать все миграции. Так делать нельзя, это плохая практика. Так можно делать только когда вы разрабатываете локально, и не хотите создавать кучу лишних миграций. А просто создать все заново. При удалении папки migrations у вас будет выходить такое сообщение постоянно. Чтобы исправить, нужно создать самому папку migrations, и в ней создать файл __init__.py. При помощи __init__.py питон понимает что это не просто папка, а модуль питона.

I am trying to implement video recording but getting this error. i have 2 buttons called Front Camera ,Back Camera. On click i am calling below method. first it displays the camera correctly but while switching camera it gives me the error. Please help how to fix the problem ?

function StartVideoCamera(obj) {
    var id = $(obj).attr('id');
    var camNode = $(obj).attr('cammode');
    if (camNode != 'user') {
        camNode = eval('{ exact: "environment" }')
    }
    var video = document.querySelector('#video' + id);
    var constraints = { audio: true, video: { width: videoHeight, height: videoWidth, facingMode: camNode 
    } };
    navigator.mediaDevices.getUserMedia(constraints)
    .then(function (mediaStream) {
        window.stream = null;
        video.srcObject = null;
        recordButton.disabled = false;
        window.stream = mediaStream;
        video.srcObject = mediaStream;
        video.onloadedmetadata = function (e) {
            video.play();
        };
    })
    .catch(function (err) {
         alert(err.name + ": " + err.message)
         console.log(err.name + ": " + err.message);
     });
}

asked Dec 30, 2020 at 11:53

santosh's user avatar

5

You need to stop the previous mediaStreamObj before calling getUserMedia again.

This happens when your other(front/back) is already in use. You need to release the camera first.

stream.getTracks()
.forEach(track => track.stop());

Here stream is what you got from getUserMedia

This stops all the devices (you can check that the camera light goes off on the desktop) and (on mobile devices).

answered Nov 4, 2022 at 6:42

Shakil Alam's user avatar

Shakil AlamShakil Alam

3084 silver badges8 bronze badges

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Pick a username
Email Address
Password

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Добрый день, появилась проблема: chrome видит камеру, но не видит поток с нее (на любом сайте).
В консоли ошибка notreadableerror.
Знаю, что она может быть из-за того, что камеру использует другое приложение, но убив все процессы, использующие камеру результата 0. Причем, yandex браузер, также, отказывается работать. Какие решения проблемы могут быть?

P.S. новое значение в реестре EnableFrameServerMode пробовал, usb порты менял, драйвер с официального сайта ласт

chrome 80.0.3987.163
flash player 32.0.0.344
Win 10 x64 18362.720
Камера Logitech C270

Solution 1

Update — 19/11/2020

WKWebView can use getUserMedia in iOS 14.3 beta 1.

  • https://bugs.webkit.org/show_bug.cgi?id=208667
  • https://bugs.chromium.org/p/chromium/issues/detail?id=752458

Update — 04/06/2020

Another bug ticket has been filed specifically for WKWebView. No support.
https://bugs.webkit.org/show_bug.cgi?id=208667

Updates to standalone mode gaining getUserMedia access in iOS 13.4
https://bugs.webkit.org/show_bug.cgi?id=185448#c6

Update — 14/09/2019

There are changes to Safari on iOS 13 & Safari 13: https://developer.apple.com/documentation/safari_release_notes/safari_13_release_notes

SFSafariViewController has gained getUserMedia functionality (!!!, however I need to confirm this, please see below for reports of it working)

https://bugs.webkit.org/show_bug.cgi?id=183201

However WKWebView does not seem to gain getUserMedia functionality:

https://bugs.chromium.org/p/chromium/issues/detail?id=752458
https://bugs.webkit.org/show_bug.cgi?id=185448

iOS 13 and Safari 13 release notes:

https://developer.apple.com/documentation/ios_ipados_release_notes/ios_13_release_notes
https://developer.apple.com/documentation/safari_release_notes/safari_13_release_notes

Update — 04/11/2018 — Links to working Ionic, Cordova and Native android examples with instructions

GitHub link to working Cordova example

GitHub link to working Android example

GitHub link to a working Ionic example

Steps to achieve getUserMedia access on Android via the Cordova framework are:

  • Follow Cordova Android install instructions (link)
  • Add Permissions to AndroidManifiest.xml (link)
  • Save WebRTC Adapter.js file to ./www/js/adapter.js and include in ./www/index.html
  • Add cordova plugin add cordova-plugin-android-permissions
  • Add plugin permission code, and the necessary getUserMedia code inside of the ./www/js/index.js file. Make sure you use getUserMedia adapter. Please see this file as an example (link).

Please see the full line by line instructions with a success and error image inside the GitHub project.


I am not sure how much of this relates to Cordova… However I had this error when I made my own Android getUserMedia test app (link). It is dependant mainly on the native app user permissions, then how the parent app creates the webviews, which version of webrtc is packaged within your app, and how you call getUserMedia.

JavaScript side of the application:
Rather than doing browser shim code yourself make sure you use the WebRTC adapter (link). This removes a lot of common problems. You can see an example here (link). I also recommend looking at the WebRTC Samples here (link).

Native side of the application:
You will need Mic and Camera user permissions for Video and Audio. This is the main culprit. You need to make sure they have been accepted before the creation of the WebView. Thus all permission checking, popups, etc, need to happen before the creation of the WebView. If permissions are granted after you most likely need to reboot the App, etc.

When you build and deploy your application go to App Settings and manually turn on the permissions if you haven’t been prompted already. Then it should work.

I wasn’t able to get Video/Audio emulation working in the emulator only on the actual device. I also only encountered the NotReadableError on Android utilising a WebChromeView before permissions have been accepted. Lastly The min API version for Android is 21 (Lollipop) for this functionality as the parent application needs to allow run-time permissions via WebView onPermissionRequest (link).

As numerous in-app browsers (Facebook, Pinterest, etc) do not handle onPermissionRequest on Android WebRTC via a website typically doesn’t work. On iOS it is guaranteed (as of April 2018) not to work as Apple have only allowed WebRTC access through the Safari only. Thus Cordova is limited to Android API 21 if it handles the permissions correctly.

Solution 2

I wanted to add the solution to my saga of fighting this particular error. I am using Ionic to build a WebRTC chat app, and have got this error with my native Android build. Here are the things that made all the difference.

Install Ionic’s AndroidPermissions plugin…

$ ionic cordova plugin add cordova-plugin-android-permissions
$ npm install --save @ionic-native/android-permissions

Don’t forget to add it to app.module.ts as a provider

In your component’s .ts file…

import { AndroidPermissions } from '@ionic-native/android-permissions';

...

iosCordova = false; // I use these for easy if-else logic later
androidCordova = false; // but I want you to see how I handle the logic

constructor(private platform:Platform, private androidPermissions: AndroidPermissions, etc...) {
        navigator.getUserMedia = ((<any>navigator).getUserMedia || (<any>navigator).webkitGetUserMedia || (<any>navigator).mozGetUserMedia || (<any>navigator).msGetUserMedia);
        this.iosCordova = this.platform.is('ios') && typeof cordova !== 'undefined';
        this.androidCordova = this.platform.is('android') && typeof cordova !== 'undefined';
        platform.ready().then(() => {
            if( this.androidCordova ){ // is Android Native App
                // alert("Android Native")
                androidPermissions.requestPermissions(
                [
                    androidPermissions.PERMISSION.CAMERA, 
                    androidPermissions.PERMISSION.MODIFY_AUDIO_SETTINGS,
                    androidPermissions.PERMISSION.RECORD_AUDIO
                ]
                ).then(()=>{
//getDevices uses Enumerate Devices and initWebRTC starts the chat connections, etc...
                    this.getDevices().then(() => this.initWebRTC())
                })
            }
       }) 
    }


ngOnInit() {
        if( !this.androidCordova ){ // is NOT Android Native App
            // alert("NOT Android Native")
            try {
                this.getDevices().then(() => this.initWebRTC())     
            } catch(e) {
                alert(e);
            }
        }
    }
...

Inspect your config.xml at myAppName/config.xml and add xmlns:android=»http://schemas.android.com/apk/res/android» to your widget tag and add the permissions request. I had issues trying to include them in the previously existing tags, and just add these permissions requests right under the closing tags (creating my own second set)

<widget id="your.app" version="1.2.3" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0">
...
</platform> // previously existing platform name="android" closing tag
<platform name="android">
    <custom-config-file parent="/manifest" target="AndroidManifest.xml">
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
    </custom-config-file>
</platform>
<platform name="ios"> // previously existing platform name="ios" opening tag

Now, you need to inspect your AndroidManifest.xml file at myAppName/platforms/android/app/src/main/AndroidManifest.xml and look for these permissions. If they are not there, add them

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Having these permissions declared in the manifest is critical to not being ignored. Apparently Android 26 is getting strict on permissions, and you can’t just ask willy-nilly for them. According to the documentation I’ve been reading, if you are not actually using the permission from within the code you are calling it from, your request will be dropped by the OS and the user will never see it.

Anyway, I’m very junior to all this Ionic and native device development, so if anyone has anything enlightening to add, please do so! Thanks everyone!

Related videos on Youtube

Cannot start the source aplication for this object

03 : 37

Cannot start the source aplication for this object

How to Fix Camera & Webcam Not Working In Windows 10/8.1/7

01 : 43

How to Fix Camera & Webcam Not Working In Windows 10/8.1/7

How To FIX Camera Not Working (error 0xA00F4292, 0xA00F4244, and 0xC00DABE0) on Windows 10

08 : 33

How To FIX Camera Not Working (error 0xA00F4292, 0xA00F4244, and 0xC00DABE0) on Windows 10

omegle all error solution | error with camera could not start video source, omegle camera issue 😍👍

07 : 31

omegle all error solution | error with camera could not start video source, omegle camera issue 😍👍

Capturing and Saving User Audio or Video with JavaScript

19 : 18

Capturing and Saving User Audio or Video with JavaScript

Steve Griffith — Prof3ssorSt3v3

How to All Problem of Web Camera (Not Working, Crashing, Another App Using Camera)

04 : 40

How to All Problem of Web Camera (Not Working, Crashing, Another App Using Camera)

HTML : NotReadableError: Failed to allocate videosource

01 : 35

HTML : NotReadableError: Failed to allocate videosource

Module not found Error Cant resolve css-loader - CSS

02 : 56

Module not found Error Cant resolve css-loader — CSS

Fix Could not fill because the history state does not contain a correspondi...Photoshop VietNam

01 : 00

Fix Could not fill because the history state does not contain a correspondi…Photoshop VietNam

Sửa lỗi The task factory  CodeTaskFactory  could not be loaded trong Visual studio 2017 | IT Vlogs

05 : 29

Sửa lỗi The task factory CodeTaskFactory could not be loaded trong Visual studio 2017 | IT Vlogs

Webcam.js Error

02 : 28

Webcam.js Error

Education And Jobs Updates by VS

Comments

  • I have added this piece of code in my project

    if (navigator.mediaDevices === undefined) {
      navigator.mediaDevices = {};
    }
    
    if (navigator.mediaDevices.getUserMedia === undefined) {
      navigator.mediaDevices.getUserMedia = function (constraints) {
    
        var getUserMedia = (
          navigator.getUserMedia ||
          navigator.webkitGetUserMedia ||
          navigator.mozGetUserMedia
        );
    
        if (!getUserMedia) {
          return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
        }
    
        return new Promise(function (resolve, reject) {
          getUserMedia.call(navigator, constraints, resolve, reject);
        });
    
      };
    }
    

    Then I’m trying to access a video stream using getUserMedia

    navigator.mediaDevices.getUserMedia({
        video: true,
        audio: false
    }).then(stream => {
        // do stuff
    }).catch(error => {
        console.log(error.name + " " + error.message);
    });
    

    When I test this in my emulators it works on android versions 5 and up, however when I run it on an actual device I get this error

    NotReadableError Could not start source

    I have added the cordova-plugin-media-capture plugin to make sure my app will request the appropriate permissions, however I don’t want to use the plugin I’d rather use the getUserMedia API.

    So far my researches show that the reason for this error is that some other app is already using the camera but that’s not the case, I even went a step further and restarted the device, then opened my app, making sure there are no other running apps and I still got the error.

    Has anyone had this issue?

    • Yes I have the issue on ionic 2, cordova 7.

    • @hthetiot did you resolve it?

    • So far I just found that video: true, audio: false work but if I enable audio: true, I get «NotReadableError Could not start source»

    • Also confirm works on emulator but not on device.

    • Also having this issue on ionic and looking for a solution

    • @php_nub_qq did my answer below help?

    • @php_nub_qq I have updated my earlier example with a working link to a Cordova project with the steps to recreate it. Please could it be marked as the answer :) The reason for the NotReadableError instead of the PermissionDeniedError is that your app most likely has the correct permissions in the AndroidManifiest.xml. However you are not catering for the runtime permissions from the Chrome webview. You need to cater for both to get the camera.

    • @Marcus sorry unfortunately I do not have time now to test this but I will accept it to honor your effort

    • @php_nub_qq Appreciated! Sorry it took so long for the end answer. Doing the same for Ionic now as I keep hitting this problem with my clients and my web based AR SDK’s…

  • i have been struggling with this error for two days and your answer helped a lot. It was permission issue on android device. thanks @Marcus

  • this pushed me in the right direction! Only needed to add more permissions for audio aswell as video but now it’s working :D thanks

  • @Wrong As Cordova packages your website as an application it is served inside of a WKWebView/UIWebView. On iOS these views are not allowed to have getUserMedia by Apple due to security concerns. You can override these security permissions on Android but not in iOS. If you were to build this App natively, and/or build a WebRTC plugin for iOS you can achieve the same end result in capturing the camera feed and passing it to the frontend. However this is a significant undertaking.

  • Same for me — been struggling with it for days. What helped most is requesting the permissions before rendering anything in the app.

  • For android it worked. I just need myAppName/platforms/android/app/src/main/AndroidManifest.xml changes. Was not necessary config.xml changes

  • Your post also pointed me to the right direction, I was missing the CAMERA permission in the AndroidManifest.xml file. I thought it was not mandatory as it’s a runtime «dangerous» permission. I should have read the doc better : developer.android.com/guide/topics/media/camera

Recents

Понравилась статья? Поделить с друзьями:
  • Notebook panel ошибка ноутбука dell
  • Not when engine on ошибка мерседес
  • Not supported between instances of list and int ошибка
  • Not response ошибка на сайте
  • Not null constraint failed ошибка