|
|
|
| Привет всем!
подскажите пожалуста, как можно с помощью "javascript" проиграть один файл звука но лиш при нажатии определённой кнопки. На пример "Z"
Зарание Благодарен. | |
|
|
|
|
|
|
|
для: cccp
(13.11.2005 в 03:16)
| | Кнопка должна на клавиатуре нажиматься или кликаться мышкой на экране? | |
|
|
|
|
|
|
|
для: codexomega
(13.11.2005 в 03:24)
| | нажиматься | |
|
|
|
|
|
|
|
для: cccp
(13.11.2005 в 03:34)
| | Этот код показывает какая кнопка на клавиатуре была нажата. Номера - это код ASCII.
<script type="text/javascript">
document.onkeyup = KeyCheck;
function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
case 16:
document.Form1.KeyName.value = "Shift";
break; case 17:
document.Form1.KeyName.value = "Ctrl";
break; case 18:
document.Form1.KeyName.value = "Alt";
break; case 19:
document.Form1.KeyName.value = "Pause";
break; case 37:
document.Form1.KeyName.value = "Arrow Left";
break; case 38:
document.Form1.KeyName.value = "Arrow Up";
break; case 39:
document.Form1.KeyName.value = "Arrow Right";
break; case 40:
document.Form1.KeyName.value = "Arrow Down";
break; }
}</script>
|
А это код для звука:
<script LANGUAGE="JavaScript"><!--
// Preload and play audio files with event handler (MouseOver sound)
// designed by JavaScript Archive, (c)1999
// Get more free javascripts at http://jsarchive.8m.com
var aySound = new Array();
// Below: source for sound files to be preloaded
aySound[0] = "sounds/hover.WAV";
aySound[1]="sounds/open.wav";
aySound[2]="sounds/start.wav";
// DO NOT edit below this line
document.write('<BGSOUND ID="auIEContainer">')
IE = (navigator.appVersion.indexOf("MSIE")!=-1 && document.all)? 1:0;
NS = (navigator.appName=="Netscape" && navigator.plugins["LiveAudio"])? 1:0;
ver4 = IE||NS? 1:0;
onload=auPreload;
function auPreload() {
if (!ver4) return;
if (NS) auEmb = new Layer(0,window);
else {
Str = "<DIV ID='auEmb' STYLE='position:absolute;'></DIV>";
document.body.insertAdjacentHTML("BeforeEnd",Str);
}
var Str = '';
for (i=0;i<aySound.length;i++)
Str += "<EMBED SRC='"+aySound[i]+"' AUTOSTART='FALSE' HIDDEN='TRUE'>"
if (IE) auEmb.innerHTML = Str;
else {
auEmb.document.open();
auEmb.document.write(Str);
auEmb.document.close();
}
auCon = IE? document.all.auIEContainer:auEmb;
auCon.control = auCtrl;
}
function auCtrl(whSound,play) {
if (IE) this.src = play? aySound[whSound]:'';
else eval("this.document.embeds[whSound]." + (play? "play()":"stop()"))
}
function playSound(whSound) { if (window.auCon) auCon.control(whSound,true); }
function stopSound(whSound) { if (window.auCon) auCon.control(whSound,false); }
//-->
</script>
|
В массив закладываются звуки и вызываются затем по своему ID.
Пример вызова звука (при наведении мышки):
a href="index.php" onMouseOver="playSound(0)" onMouseOut="stopSound(0)">Home</a>
|
Подгоните код под себя.
Т.е вызывайте звук при нажатии клавиши.
Вот таблица ASCII:
http://www.lookuptables.com/ | |
|
|
|
|
|
|
|
для: codexomega
(13.11.2005 в 03:44)
| | Не совсем пойму...
Мне что вот это всё надо использовать? Только для ттого что бы один файл съыграл при нажатии кнопки "Z", да? | |
|
|
|
|
|
|
|
для: cccp
(13.11.2005 в 04:19)
| | Я вам дал универсальное оружие.
Вам надо только взять ту часть которая вам нужна. | |
|
|
|
|
|
|
|
для: codexomega
(13.11.2005 в 05:06)
| | Ловите ваш код!
Работает когда нажимаете на клавишу Z.
Не забудьте создать папку sound, в которую положите звуковой файл и назовите его hover.WAV:)
Очень надеюсь что вы разбираетесь в функциях и в передачи параметров!
А то разжевывать придется:)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Browser Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<body>
<script language="javascript">
document.onkeyup = KeyCheck;
function KeyCheck(e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
if(KeyID == 90 || KeyID == 122 ){
playSound(0);
}
}
// - BEGIN SOUND CODE
var aySound = new Array();
// Below: source for sound files to be preloaded
aySound[0] ="sounds/hover.WAV";
aySound[1]="sounds/open.wav";
aySound[2]="sounds/start.wav";
// DO NOT edit below this line
document.write('<BGSOUND ID="auIEContainer">')
IE = (navigator.appVersion.indexOf("MSIE")!=-1 && document.all)? 1:0;
NS = (navigator.appName=="Netscape" && navigator.plugins["LiveAudio"])? 1:0;
ver4 = IE||NS? 1:0;
onload=auPreload;
function auPreload() {
if (!ver4) return;
if (NS) auEmb = new Layer(0,window);
else {
Str = "<DIV ID='auEmb' STYLE='position:absolute;'></DIV>";
document.body.insertAdjacentHTML("BeforeEnd",Str);
}
var Str = '';
for (i=0;i<aySound.length;i++)
Str += "<EMBED SRC='"+aySound[i]+"' AUTOSTART='FALSE' HIDDEN='TRUE'>"
if (IE) auEmb.innerHTML = Str;
else {
auEmb.document.open();
auEmb.document.write(Str);
auEmb.document.close();
}
auCon = IE? document.all.auIEContainer:auEmb;
auCon.control = auCtrl;
}
function auCtrl(whSound,play) {
if (IE) this.src = play? aySound[whSound]:'';
else eval("this.document.embeds[whSound]." + (play? "play()":"stop()"))
}
function playSound(whSound) { if (window.auCon) auCon.control(whSound,true); }
function stopSound(whSound) { if (window.auCon) auCon.control(whSound,false); }
// - END SOUND CODE
</script>
</body>
</html>
|
| |
|
|
|
|
|
|
|
для: codexomega
(13.11.2005 в 05:21)
| | Спасибо огромное.
Так мне понятнее всё будет. | |
|
|
|
|
|
|
|
для: cccp
(13.11.2005 в 21:37)
| | Что не могу понять, ето почему в скрипте 3 файла на звук?
И какой из них вклучается от какой кнопки?
первый от "Z", а другие?
aySound[0] ="sounds/hover.WAV";
aySound[1]="sounds/open.wav";
aySound[2]="sounds/start.wav";
|
| |
|
|
|
|
|
|
|
для: cccp
(13.11.2005 в 22:29)
| | Это опцианально.
Если хотите прикрепить дополнительные звуки, например на нажатие кнопки А, то соответственно и передавайте в параметрах:
playSound(1) или playSound(2)
Число звуковых файлов может быть большим и вы можете менять их и применять как вам захочется.
Может вы захотите пианино симулировать на клавиатуре:)
Извините, если не очень понятно, книг я не писал:) | |
|
|
|
|
|
|
|
для: codexomega
(13.11.2005 в 22:45)
| | Спасибо ещё раз. | |
|
|
|
|
|
|
|
для: codexomega
(13.11.2005 в 05:21)
| |
<!doctype html public "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>Untitled web-page</title>
</head>
<script>
var soundFiles="";
function playMusic(soundFiles)
{
bodyClick.innerHTML="<embed src='"+soundFiles+"' autostart='true' hidden='true' balance=1000 loop=4 volume=10>";
}
function stopMusic()
{
bodyClick.outerHTML="<b id='bodyClick'></b>"; // play sound
}
function document.onclick()
{
bgsd.src="sound01.mp3"; // play music
}
function document.ondblclick()
{
bgsd.src=""; // play music
}
document.write("<bgsound id='bgsd' src='"+soundFiles+"'>")
</script>
<style>
p {border-style: solid;
border-color:#222222;
border-width: 1px;
padding-left: 0px;
margin-right: 800px;
left: 800px;
}
</style>
<body bgcolor="#808080">
<p onclick="playMusic('fire.wav')" align=center>play sound<b id="bodyClick"></p></b>
<p onclick="stopMusic()" align=center>stop sound</b>
</body>
</html>
|
так намного просче как мне кажется но за идею очень признателен | |
|
|
|
|
|
|
|
для: MAX LM
(24.12.2005 в 16:16)
| | Если делать проще, то модифицируем немного пример из [url]read.php?id_forum=2&id_theme=10775[/url]
<embed id=snd src=78798016ced3e9d5e835622fba236d70.mp3 autostart=false loop=true height=42 controller=true hidden></embed><br>
<input type=button onClick=document.getElementById("snd").play(); value=Play>
<input type=button onClick=document.getElementById("snd").stop(); value=Stop>
<input type=button onClick=document.getElementById("snd").pause(); value=Pause>
| В FF тоже собирается работать, но просит загрузить QuickTime на 25 МБа. Как это обойти и запустить в FF медиаплеер? | |
|
|
|
|
|
|
|
для: 12345
(24.12.2005 в 20:01)
| | Здесь говорится о настройках Файрфокса, для проигрывания файлов в Windows Media Player.
http://forums.mozillazine.org/viewtopic.php?t=206216#stream
Не тестировал пока. | |
|
|
|
|
|
|
|
для: codexomega
(24.12.2005 в 20:30)
| | Что-то не удалось запустить Windows Media Player Plugin for FF 1.06 - ни Windows Media Player Plug-in for Netscape Navigator не помог, ни ActiveX Plugin (Firefox 1.0-1.0.7, 1.5) , описанный на http://forums.mozillazine.org/viewtopic.php?t=206213 - Full Step-By-Step Guide: Embedded Windows Media in Firefox - Возможно, что-то не так делал. Плагин установился, а результатов нет, всё равно просит QuickTime и ничего более в ответ на <embed>.
Поставил QuickTime Alternative (1.67, 11 МБа), он вытеснил Windows Media Player из IE как embed по умолчанию, и с ним случился такой эффект, что если ставишь <embed id=snd src=StoryBTL_S.wav autostart=false loop=true height=42 controller=true hidden=true[/b]></embed>, то он и от кнопок из кода выше ([b]INPUT type=button) не запускается, зато если hidden убрать, то кнопки на JavaScript тоже работают. А сам плеер приобретает вид Аппловского компактненького - см вложение. (Вместо MS-медиаплеера.) В FF он от своих кнопок запуска начинает работать, а от JS-кнопок - нет. Видно, JS в FF не поддерживает методы play(), stop(), pause().
Нехорошая вещь - эти плагины, например, <object data=78798016ced3e9d5e835622fba236d70.mp3 type="audio/mpeg"> перестал работать в IE. Теперь настраивай их. : )
Покопавшись немного, нашёл полезный FAQ по запуску плееров: http://www.boutell.com/newfaq/creating/scriptsound.html. Из него явствует, что методы запуска для FF надо писать с большой буквы - Play(), Stop(), и, кроме того, указать в embed enablejavascript=true, иначе управления из JS в FF не будет, но последнее не соответствует действительности. Возможно, это работало в старых Мозиллах. Также, видим, что в разных плеерах могут быть разные методы (DoPlay() для RealPlayer).
Действительно, когда у меня стоял MS-медиаплеер, работал метод pause(), а stop() переводил на начало песни. Сейчас, с QuickTime Alternative Stop() работает как pause(), pause() не работает (в IE тоже), а вместо старого stop() действует Rewind(). Итак, имеем такой код (IE, FF):
<embed id=snd src=78798016ced3e9d5e835622fba236d70.mp3 StoryBTL_S.wav autostart=false loop=true height=42 controller=true enablejavascript=true hid den=true></embed><br>
<input type=button onClick=d.getElementById("snd").Play(); value=Play>
<input type=button onClick=d.getElementById("snd").Stop(); value=Stop>
<input type=button onClick=d.getElementById("snd").Rewind(); value=Rewind>
| В Опере 7.54 не запускается, хотя плагин QuickTime Alternative в ней установился. В ней, очевидно, папраметры приведённого тега не устраивают.
Чтобы запускались нужные расширения в браузерах, для этого плагина нужно повключать MIME types в его Settings. К сожалению, данная версия не может культурно отключаться, хотя чекбокс в настройках для этого есть. Отключённый, он всё равно появляется на месте плеера на веб-странице.
Да, а по клику на клавиатуре будет так (IE, FF):
<embed id=snd src=78798016ced3e9d5e835622fba236d70.mp3 StoryBTL_S.wav autostart=false loop=true controller=true hid den=true></embed><br>
<input type=button onClick=d.getElementById("snd").Play(); value=Play(Z)>
<input type=button onClick=d.getElementById("snd").Stop(); value=Stop(S)>
<input type=button onClick=d.getElementById("snd").Rewind(); value=Rewind(A)>
<script>(d=document).onkeypress=function(e){if(!e)e=event;var key=e.keyCode?e.keyCode:e.charCode;
with(d.getElementById("snd")){
if(key==122||key==90||key==1103||key==1071)Play();
if(key==115||key==83||key==1099||key==1067)Stop();
if(key==97||key==65||key==1092||key==1060)Rewind();
}}
</script>
|
| |
|
|
|