Jump to content

Obtenção do vídeo em execução


zppinto
Go to solution Solved by pmg,

Recommended Posts

A programação passa basicamente por javascript e mysql, e o vídeo apresentado é em HTML5.

O que se passa é que não estou a conseguir fazer a leitura correcta do vídeo que está a ser executado, e imprimir a informação correspondente ao mesmo, através da consulta da base de dados. (tabela rodeada a vermelho) Isto porque o vídeo que é constantemente imprimido é o "movie1.mp4" e não percebo porquê.

Para a reprodução dos vídeos eu faço uma pesquisa a uma determinada pasta e reproduzo todos os videos disponíveis na mesma.

Código game.php

<?php
$files = glob('vids/*.mp4'); //ficheiros da pasta "vids"
require("includes/inc.php");
if ($_SESSION['username'] == null){
# Redirect the user to the login area if they're not logged in
header('Location: login.php');
}
# -> Check if the user is trying to logout
if ($_GET['page'] == "logout"){
// Unset the session and redirect the user to the login page
unset($_SESSION['username']);
header('Location: login.php?success=logout');
}
# -> Check if the user is trying to view their account
if ($_GET['page'] == "account_save"){
// Post variables
$email = trim(sanitize($_POST['email']));
$password = trim(sanitize($_POST['password']));
// Check if the email field is blank
if ($email == null){
 header('member.php?page=account&error=email_blank');
} else {
 # Check if email is in the valid format
 if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
 // Email is invalid
 header('Location: member.php?page=account&error=email_invalid');
 } else {
 # Update account
 $update_email = mysql_query("UPDATE users SET email = '$email' WHERE `username` = '$user[username]'") or die("Couldn't update mysql database");
 # Update their password if it wasn't blank
 if ($password != null){
	 $update_password = mysql_query("UPDATE users SET password = '" . password($password) . "' WHERE `username` = '$user[username]'") or die("Couldn't update the password");
 }
 header('Location: member.php?page=account&success=updated');
 }
}
} else {
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

function myEndedListener(){
var myVideo = document.getElementsByTagName('video')[0];
myVideo.addEventListener('ended',myNewSrc,false);
}
var position = 0;
var videoList=<?php echo json_encode($files) ?>; //array da pasta "vids"

function myNewSrc() {
var myVideo = document.getElementsByTagName('video')[0];
if(++position >= videoList.length) {
position = 0;
}
myVideo.src=videoList[position];
myVideo.load();
myVideo.play();
array = []; //array a zero para limpar as tags
document.getElementById('myDiv').innerHTML = ""; //limpa o código html das tags
return(videoList[position]);
}
function getFileName(){
var aftervids = videoList[position].substr(videoList[position].indexOf("/") + 1); //Remove "vids/" e deixa só o nome do ficheiro
return aftervids;
}

//TIMER COUNTDOWN
var mins
var secs;
function cd() {
mins = 1 * m("10"); // mudar os minutos
secs = 0 + s(":04"); // mudas os segundos (acrescentar sempre 1s a mais)
redo();
}
function m(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(0, i));
}
function s(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(i + 1, obj.length));
}
function dis(mins,secs) {
var disp;
if(mins <= 9) {
disp = " 0";
} else {
disp = " ";
}
disp += mins + ":";
if(secs <= 9) {
disp += "0" + secs;
} else {
disp += secs;
}
return(disp);
}
function redo() {
secs--;
if(secs == -1) {
secs = 59;
mins--;
}
document.cd.disp.value = dis(mins,secs); // setup additional displays here.
if((mins == 0) && (secs == 0)) {
window.alert("O tempo terminou. Pressione OK");
window.location = "gameover.php"
} else {
cd = setTimeout("redo()",1000);
}
}
function init() {
myEndedListener(); //Inicia o processo em sequencia
cd();
}
window.onload = init;
//GET TIMECODE, USERNAME, TAG, GAME ID
$(document).ready(function() {
	 function getCurTime(){

var myVid=document.getElementById("video1");
return myVid.currentTime.toFixed(0);;
}

function username(u)
{
var u = '<?php echo $_SESSION['username'] ?>';
return u;
}

function gameID(gid)
{
var gid = '<?php echo(rand(1,1000000)) ?>';
return gid;
}

// COOKIE GAME ID
function CookieSet (cName, cValue, cPath, cExpires)
{
document.cookie = cName + "=" + cValue ;
}
CookieSet("GameID",gameID(),"","");

$("#form").submit(function(){
	 /* Isto para que não precises do hidden, do outro lado recebes na mesma pelo post o valor do campo timecode pelo $_POST["timecode"]*/
 var curTime = getCurTime();
 $.ajax({
type: "POST",
		 url: "insert.php",
		 data: {
 tag: $("#tag").val(),
			 timecode: curTime,
 username: username(),
 filename: getFileName(),
 gameid: gameID()
			 }
		 }).done(function( msg ) {
		 // Output do teu insert.php
		 alert("Recebido: " + msg);
		 });
	 return false; // Impede a mudança de página
});
});
//GET TAGS AND SHOW THEM
var array = new Array();
function insert(val){
array[array.length]=val;
}
function show() {
var string="";
for(i = 0; i < array.length; i++) {
string =string+array[i]+"<br>";
}
if(array.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
function show2(string)
{
document.getElementById('myInfo').innerHTML = string;
}


//SHOW SCORE
function showScore() {
/*var string="<h3>SCORE<h3>";
for(i = 0; i < array.length; i++) {
string =string+array[i]+"<br>";
}
if(array.length > 0)
document.getElementById('myScore').innerHTML = string;
*/
}
function myTags() {
}
function videoDetails(){
	 $.ajax({
type: "GET",
		 url: "get.php",
		 data: {
 filename: getFileName(),
			 }
		 }).done(function( msg ) {
show2(msg);
		 });
	 return false; // Impede a mudança de página
};

videoDetails();

</script>
</head>
<body>
<div id="wrap">
<div id="header">
 <?php echo $user[username],"\n";?> is playing...
 <div id="header_small"><a href="member.php">Home</a> | <a href="member.php?page=account">My Account</a> | <a href="member.php?page=logout">Logout</a></div>
</div>
<!-- Display Messages -->
<?php
 # -> Messages
 if ($_GET['error'] == "email_blank"){ echo "<div class='error'>Please do not leave the email field blank</div>\n"; }
 elseif ($_GET['error'] == "email_invalid"){ echo "<div class='error'>Please use a valid email format - name@domain.com</div>\n"; }
 elseif ($_GET['success'] == "updated"){ echo "<div class='success'>Your account details have been successfully updated</div>\n"; }
?>
<div class="content_area">
 <?php
 if ($_GET['page'] == "account"){
	 # -> Modify account
	 echo "Update your email address and password. Leave the password field blank if you do not wish to change it.", "\n";
	 echo "<div class='spacer'></div>", "\n";
	 echo "<form action=\"member.php?page=account_save\" method=\"post\" autocomplete=\"off\">", "\n";
	 echo "<strong>Email Address</strong><br />\n<input type=\"text\" name=\"email\" size=\"40\" maxlength=\"12\" value=\"$user[email]\" onblur=\"if (this.value == '') {this.value = '$user[email]';}\" onfocus=\"if (this.value == '$user[email]') {this.value = '';}\">";
	 echo "<div class='spacer'></div>", "\n";
	 echo "<strong>Password</strong><br />\n<input type=\"password\" name=\"password\" size=\"40\" maxlength=\"12\">";
	 echo "<div class='spacer'></div>", "\n";
	 echo "<input type=\"submit\" value=\"Save Information\">", "\n";
	 echo "</form>";
 } else {
 }
 ?>
<table cellpadding="0" cellspacing="2" border="2" align="center">
<tr>
<td align="center" width="100" height="112" class="smbox">Time Left<br><br>
<form name="cd">
<input id="txt" readonly="true" type="text" value="10:00" border="0" name="disp">
</form>
</td>
<td align="center" width="600" class="smbox">
VIDEO TAG GAME
</td>
<td align="center" width="100" height="112" class="smbox">Points<br>
<div align="center">
<iframe src ="" width="125" height="50" frameborder="0" name="gpoints_frame" scrolling="no"></iframe>
</div>
</td>
</tr>

</table>


<table cellpadding="0" cellspacing="0" border="2" align="center" width="100%">
<tr>
<td>
<table cellpadding="0" cellspacing="2" border="0" align="center" width="100%">
<tr>
<td align="center" valign="top" class="gamebx" width="200">
<p class="gmhead" align="center" ><strong>Video Details</strong></p>
 <div align="center" id="myInfo"></div>
</td>
<td align="center" class="vidbx">
 <!-- video section -->
 <div id="centervid">
<video id="video1" width="400" height="300" controls="controls" autoplay="autoplay">
<source src="intro.mp4" type="video/mp4"/>
O browser não suporta HTMl5.
</video>
 </div>
</td>
<td align="center" valign="top" class="gamebx" width="200">
<p class="gmhead"><strong>Tags Entered</strong></p>
 <div align="center" id="myDiv"></div>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table cellpadding="0" cellspacing="10" border="2" align="left" width="100%" class="tagentbx">
<tr>
 <td class="smbox">You are on level <br><span class="levno">1</span>
 </td>
 <td align="center" class="gamebx" valign="top">
 <table>
 <tr>
 <form id='form' name='form' method="post">
Tag: <input type="text" name="tag" id="tag" onfocus="this.value='';"/>
	 <input type="submit" value="Submeter" onclick="insert(this.form.tag.value),show();"/><p>
</form>
 </tr>
 </table>
</td>
<td class="smbox">
	 <table align="center" cellpadding="4">
 <tr>
	 <td valign="top" height="22">
	 <a href="#" onclick="myNewSrc()"><img src="images/btn_skip.gif" width="136" height="22" alt="Button - Skip This Video" border="0"></a>
	 </td>
 </tr>
 <tr>
	 <td valign="top" height="22">
	 <a href="gameover.php" target="_parent"><img src="images/btn_end.gif" width="136" height="22" alt="Button - End Game" border="0"></a>
 </td>
 </tr>
 </table>
</td>
</tr>
</table>
</td>
</tr>
</table>


<div id="myScore"></div>

 </div>
</div>

</body>
</html>
<?php
} // End change
?>
Link to comment
Share on other sites

  • Solution

Eu nao sei Javascript (e suponho que o teu problema seja de PHP).

Nao consegui perceber como seleccionas o video, mas a linha

$filename=$_GET["filename"];

vai meter em $filename o que esta na barra de endereco do browser.

Lembra-te que o Javascript e o PHP nao "falam" um com o outro. O PHP "despeja" o conteudo para o browser e "desliga-se". O Javascript comeca a funcionar nessa altura quando o PHP "ja nao existe".

What have you tried?

Não respondo a dúvidas por PM

A minha bola de cristal está para compor; deve ficar pronta para a semana.

Torna os teus tópicos mais atractivos e legíveis usando a tag CODE para colorir o código!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.