Как сделать так, чтобы источник видео менялся в соответствии с выбранным файлом?
Смена источника видео не работает именно на iOS 6. Выбранное в input видео в теге video появляется с ошибкой. При VarOpt.id = URL.createObjectURL(document.querySelector("input").files[i]); видео вообще не появляется в теге video.
<!DOCTYPE html> <html lang="ru"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.5"> <meta name="apple-mobile-web-app-capable" content="yes"/> <title>Test</title> </head> <body> <video controls></video> <input accept="video/*" type="file" onchange="InputSelectFileChange()" multiple> <select onchange="SelectFileChange()"></select> <script> function InputSelectFileChange() { for (var i = 0; i < document.querySelector("input").files.length; i++) { var VarOpt = document.createElement("option"); VarOpt.text = document.querySelector("input").files[i].name; VarOpt.id = document.querySelector("input").files[i]; VarOpt.value = document.querySelector("input").files[i].name; document.querySelector("select").add(VarOpt); } } function SelectFileChange() { document.querySelector("video").src = document.querySelector("select")[document.querySelector("select").selectedIndex].id; //alert(document.querySelector("input").files[0].name + " " + document.querySelector("input").files[0]); } </script> </body> </html> |
<!DOCTYPE html> <html lang="ru"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.5"> <meta name="apple-mobile-web-app-capable" content="yes"/> <title>Test</title> </head> <body> <video controls></video> <input accept="video/*" type="file" onchange="InputSelectFileChange()" multiple> <select onchange="SelectFileChange()"></select> <script> function InputSelectFileChange() { for (var i = 0; i < document.querySelector("input").files.length; i++) { var VarOpt = document.createElement("option"); VarOpt.text = document.querySelector("input").files[i].name; VarOpt.id = document.querySelector("input").files[i]; VarOpt.value = document.querySelector("input").files[i].name; document.querySelector("select").add(VarOpt); } } function SelectFileChange() { document.querySelector("video").src = document.querySelector("select")[document.querySelector("select").selectedIndex].id; //alert(document.querySelector("input").files[0].name + " " + document.querySelector("input").files[0]); } </script> </body> </html>
Ошибка на скриншоте:
Дополнительно:
Возможно IOS 6 не поддерживает данный код. Зачем вам адаптировать ваше приложение для старых платформ которые уже не используются?
Ответы:
AlTerminator, Поискал на просторах интернета, а нашёл, что IOS 6 не поддерживает "URL.createObjectURL()"
Используйте: FileReader.
function SelectFileChange() { var file = document.querySelector("input").files[document.querySelector("select").selectedIndex]; var reader = new FileReader(); reader.onload = function(e) { document.querySelector("video").src = e.target.result; }; reader.readAsDataURL(file); } |
function SelectFileChange() { var file = document.querySelector("input").files[document.querySelector("select").selectedIndex]; var reader = new FileReader(); reader.onload = function(e) { document.querySelector("video").src = e.target.result; }; reader.readAsDataURL(file); }
- не работает. Выдает ошибку 1. Причем для фотографий ваш способ работает, но для видео нет. Выяснил, что работает webkitURL.createObjectURL() только для фото.
function SelectFileChange() { var file = document.querySelector("input").files[document.querySelector("select").selectedIndex]; var reader = new FileReader(); reader.onload = function(e) { document.querySelector("video").src = e.target.result; }; reader.onerror = function(e) { alert("Ошибка " + e.target.error.code); } reader.readAsDataURL(file); }
function SelectFileChange() { var file = document.querySelector("input").files[document.querySelector("select").selectedIndex]; var reader = new FileReader(); reader.onload = function(e) { document.querySelector("video").src = e.target.result; }; reader.onerror = function(e) { alert("Ошибка " + e.target.error.code); } reader.readAsDataURL(file); }
- В данной статье указано
- Загир Меджидов, не работает. Обработчик выдает ошибку 4. Узнал через обработчик события onerror у видео. Сработало через костыль. Видео открывается по прямой ссылке в файловой системе:
<!DOCTYPE html> <html lang="ru"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.5"> <meta name="apple-mobile-web-app-capable" content="yes"/> <title>Test</title> </head> <body> <video controls onerror="VideoOnError()"></video> <input type="file" onchange="InputFileChange()" multiple> <select onchange="SelectFileChange()"> <option selected hidden disabled>Список видео</option> </select> <script> function VideoOnError(e) { alert("Ошибка " + e.target.error.code); } function InputFileChange() { for (var i = 0; i < document.querySelector("input").files.length; i++) { var VarOpt = document.createElement("option"); VarOpt.text = document.querySelector("input").files[i].name; //VarOpt.id = webkitURL.createObjectURL(document.querySelector("input").files[i]); VarOpt.id = "/var/mobile/Media/DCIM/100APPLE/" + document.querySelector("input").files[i].name; VarOpt.value = document.querySelector("input").files[i].name; document.querySelector("select").add(VarOpt); } } function SelectFileChange() { document.querySelector("video").src = document.querySelector("select")[document.querySelector("select").selectedIndex].id; } </script> </body> </html>
<!DOCTYPE html> <html lang="ru"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.5"> <meta name="apple-mobile-web-app-capable" content="yes"/> <title>Test</title> </head> <body> <video controls onerror="VideoOnError()"></video> <input type="file" onchange="InputFileChange()" multiple> <select onchange="SelectFileChange()"> <option selected hidden disabled>Список видео</option> </select> <script> function VideoOnError(e) { alert("Ошибка " + e.target.error.code); } function InputFileChange() { for (var i = 0; i < document.querySelector("input").files.length; i++) { var VarOpt = document.createElement("option"); VarOpt.text = document.querySelector("input").files[i].name; //VarOpt.id = webkitURL.createObjectURL(document.querySelector("input").files[i]); VarOpt.id = "/var/mobile/Media/DCIM/100APPLE/" + document.querySelector("input").files[i].name; VarOpt.value = document.querySelector("input").files[i].name; document.querySelector("select").add(VarOpt); } } function SelectFileChange() { document.querySelector("video").src = document.querySelector("select")[document.querySelector("select").selectedIndex].id; } </script> </body> </html>
Скриншот:
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос


Для того чтобы сделать так, чтобы источник видео менялся в соответствии с выбранным файлом, вам необходимо использовать JavaScript в сочетании с HTML5 video элементом и его свойством source.
Ниже приведен пример кода на JavaScript и HTML, который позволит вам реализовать данную функциональность:
<title>Dynamic Video Source Change</title> Video 1 Video 2 <video id="videoPlayer" controls> </video> const videoSelect = document.getElementById('videoSelect'); const videoPlayer = document.getElementById('videoPlayer'); videoSelect.addEventListener('change', function() { const selectedVideo = videoSelect.value; videoPlayer.src = selectedVideo; videoPlayer.play(); });<title>Dynamic Video Source Change</title> Video 1 Video 2 <video id="videoPlayer" controls> </video> const videoSelect = document.getElementById('videoSelect'); const videoPlayer = document.getElementById('videoPlayer'); videoSelect.addEventListener('change', function() { const selectedVideo = videoSelect.value; videoPlayer.src = selectedVideo; videoPlayer.play(); });
В данном примере создается выпадающий список (select) с двумя опциями и видео элемент (video) с исходным источником видео. При изменении выбранной опции в списке, JavaScript обрабатывает событие и изменяет источник видео в соответствии с выбранной опцией. После этого видео начинает воспроизведение.
Вы можете дополнить данный код дополнительными опциями и видео файлами, а также стилизовать элементы на странице по своему усмотрению. Надеюсь, этот пример поможет вам решить вашу проблему с динамической сменой источника видео на вашем сайте.