Здравствуйте.
Нужно, чтобы при входящем сообщении на сайте проигрывался звук, по типу, как у контакта! Как это реализовать? Скрипт проверки на наличие сообщений имеется, как в него вставить воспроизведение звукового файла?
Решил проблему так:
function soundClick() {
var audio = new Audio(); // Создаём новый элемент Audio
audio.src = 'n.mp3'; // Указываем путь к звуку "клика"
audio.autoplay = true; // Автоматически запускаем
}
Ответ
Предлагаю не создавать объект Audio каждый раз, ведь вы можете создать его однажды и использовать повторно
Ниже накиданный на скорую руку симулятор чата
function MessageClass(userName, text, avatarSrc, sendTime){
var self = this;
this.UserName = userName;
this.Text = text;
this.SendTime = sendTime.toLocaleTimeString();
this.AvatarSrc = avatarSrc;
}
var chat = new function (){
var audio = document.createElement('audio'),
source = document.createElement('source'),
tid = 0;
source.type = 'audio/mpeg';
source.src = 'http://dl.dropbox.com/u/1538714/article_resources/song.m4a';
audio.appendChild(source);
this.Messages = ko.observableArray([]);
this.Messages.subscribe(function (){
clearInterval(tid);
audio.pause();
audio.currentTime = 0;
audio.play();
// только потому что трек длинный
tid = setTimeout(function(){
audio.pause();
}, 400);
});
}
ko.applyBindings(chat, document.getElementById("chat"));
(function onMessage(){
chat.Messages.push(
new MessageClass(
faker.name.firstName() + ' ' + faker.name.lastName(),
faker.hacker.phrase(),
faker.image.avatar(),
new Date()
)
);
scrollTo(0, document.body.offsetHeight);
setTimeout(onMessage, faker.random.number(1500) + 500);
})(chat, faker);
fieldset{
position: relative;
}
fieldset:nth-child(2n){
margin-left:24px;
}
legend{
color:#0a0;
}
time{
position:absolute;
right:12px;
top:0px;
background:#FFF;
color: #a00;
display:inline-block;
padding: 0px 6px;
font-size: 12px;
}
img{
float:left;
width: 60px;
margin-right: 12px;
border-radius:30px;
height:60px;
}
А вот здесь вы и сами можете писать сообщения:
function MessageClass(userName, text, avatarSrc, sendTime){
var self = this;
this.UserName = userName;
this.Text = text;
this.SendTime = sendTime.toLocaleTimeString();
this.AvatarSrc = avatarSrc;
}
var chat = new function (){
var self = this,
tid = 0,
audio = document.createElement('audio'),
source = document.createElement('source'),
generateFakeMessage = function (){
self.Messages.push(
new MessageClass(
faker.name.firstName() + ' ' + faker.name.lastName(),
faker.hacker.phrase(),
faker.image.avatar(),
new Date()
)
);
scrollTo(0, document.body.offsetHeight);
};
source.type = 'audio/mpeg';
source.src = 'http://dl.dropbox.com/u/1538714/article_resources/song.m4a';
audio.appendChild(source);
self.Messages = ko.observableArray([]);
self.UserMessage = ko.observable('');
self.sendMessage = function(){
if (self.UserMessage()){
chat.Messages.push(new MessageClass(
'My account',
self.UserMessage(),
'//s3.amazonaws.com/uifaces/faces/twitter/psdesignuk/128.jpg',
new Date()
));
self.UserMessage('');
}
setTimeout(generateFakeMessage, 1000);
return false;
};
self.Messages.subscribe(function (){
clearInterval(tid);
audio.pause();
audio.currentTime = 1;
audio.play();
// только потому что трек длинный
tid = setTimeout(function(){
audio.pause();
}, 400);
});
generateFakeMessage();
}
ko.applyBindings(chat, document.getElementById("chat"));
fieldset{
position: relative;
}
fieldset:nth-child(2n){
margin-left:24px;
}
legend{
color:#0a0;
}
time{
position:absolute;
right:12px;
top:0px;
background:#FFF;
color: #a00;
display:inline-block;
padding: 0px 6px;
font-size: 12px;
}
img{
float:left;
width: 60px;
margin-right: 12px;
border-radius:30px;
height:60px;
}
input, button{
margin-top:6px;
width:100%;
}