启动和在Javascript停止音频 [英] Starting and Stopping Audio in Javascript

查看:133
本文介绍了启动和在Javascript停止音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绑一个onClick事件的函数。它应该播放一首歌曲。如果有一首歌曲已在播放它应该停止当前的歌曲,并开始播放新的。唯一的问题是,据我所知,只有一个暂停方式,这意味着previous歌会从暂停的位置,而不是开始恢复。有没有解决这个任何方式(如.stop()方法)?

下面是我的code:

  VAR currSong =;功能playSong(newSong){
        警报(newSong);
        如果(newSong!=){
            如果(currSong!=){
                的document.getElementById(currSong).pause();
            }
            的document.getElementById(newSong).play();
            currSong = newSong;
        }
}


解决方案

从看<一个href=\"https://developer.mozilla.org/En/XPCOM_Interface_Reference/NsIDOMHTMLMediaElement#play%28%29\">MDC为音频元素文件,看来,要做到这一点,正确的做法是通过设置 currentTime的属性:

 函数playSong(newSong){
    警报(newSong);
    如果(newSong!=){
        如果(currSong!=){
            的document.getElementById(currSong).pause();
        }
        VAR newSongEl =的document.getElementById(newSong);
        newSongEl.currentTime = 0;
        newSongEl.play();
        currSong = newSong;
    }
}

此外,这将是更好地存储在 currSong ,而不是它的ID相关的元素,除非你正在使用的ID别的东西。

I have a function tied to an onClick event. It's supposed to play a song. If there's a song already playing it's supposed to stop the current song and start playing the new one. The only problem is that as far as I know there is only a pause method and it means that the previous song will resume from the paused position and not the beginning. Is there any way around this (like a .stop() method)?

Here's my code:

var currSong="";

function playSong(newSong){         
        alert(newSong);
        if (newSong != ""){
            if(currSong != "" ) {
                document.getElementById(currSong).pause();
            }           
            document.getElementById(newSong).play();
            currSong = newSong;
        }
}

解决方案

From looking at the MDC documentation for the audio element, it appears that the correct way to do this is by setting the currentTime property:

function playSong(newSong){         
    alert(newSong);
    if (newSong != ""){
        if(currSong != "" ) {
            document.getElementById(currSong).pause();
        }           
        var newSongEl = document.getElementById(newSong);
        newSongEl.currentTime = 0;
        newSongEl.play();
        currSong = newSong;
    }
}

Also, it would be better to store the relevant element in currSong, rather than its ID, unless you are using the ID for something else.

这篇关于启动和在Javascript停止音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆