本文介绍了HTML5音频:如何只播放音频文件的选定部分(音频精灵)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发iOS节拍器网页应用。由于移动游猎只能一次播放,我试图创建一个' audio sprite' - 我可以使用单个音轨的不同段来生成不同的声音。我有一个1秒的剪辑,上面有2个半秒的声音。

I'm working on an iOS metronome web app. Since mobile safari can only play one sound at a time, I'm attempting to create an 'audio sprite' - where I can use different segments of a single audio track to generate different sounds. I have a 1 second clip with 2 half-second sounds on it.

<audio id="sample" src="sounds.mp3"></audio>

<a href="javascript:play1();">Play1</a>
<a href="javascript:play2();">Play2</a>
<a href="javascript:pauseAudio();">Pause</a>

<script>
var audio = document.getElementById('click');

function play1(){
    audio.currentTime = 0;
    audio.play();

    // This is the problem area
    audio.addEventListener('timeupdate', function (){
        if (currentTime >= 0.5) {
            audio.pause();
        }
    }, false);
}

function play2(){
    audio.currentTime = 0.5;
    audio.play();
}

function pause(){
    audio.pause();
}
</script>

在。

如您所见,我试图使用'timeupdate'事件()无济于事。

As you can see, I've attempted to use the 'timeupdate' event (jPlayer example) with no avail.

我见过,但是(A)我无法让它为我工作,(B)我宁愿远离库依赖。

I've seen Remy Sharp's post on audio sprites, but (A) I wasn't able to get it to work for me, and (B) I would prefer to stay away from a library dependency.

有什么想法吗?在此先感谢您的帮助!

Any ideas? Thanks in advance for your help!

更新

Update

我现在使用 setInterval

function play1(){
    audio.currentTime = 0;
    audio.play();
    int = setInterval(function() {
        if (audio.currentTime > 0.4) {
            audio.pause();
            clearInterval(int);
        }
    }, 10);
}

function play2(){
    clearInterval(int);
    audio.currentTime = 0.5;
    audio.play();
}

序列和设置/清除间隔存在一些问题,但出于我的目的 - 它似乎有效。

There are some issues with sequence and setting/clearing intervals, but for my purpose - it seems to work.

谢谢!

PS如果有人对此有解决方法,可以在Games和Interface Sound FX中使用。

P.S. If anyone has a fix for this, this could be used in Games and Interface Sound FX.

推荐答案

我认为有一对这里的问题。

I think there are a couple of problems here.

首先,每次用户点击Play 1时你都会添加一个事件监听器。

Firstly, you're adding an event listener every time the user clicks Play 1.

我认为

if (currentTime >= 0.5) { ...

if (audio.currentTime >= 0.5) { ...

这也有效:

<audio id="sample" src="http://dl.dropbox.com/u/222645/click1sec.mp3" controls preload></audio>

<a href="javascript:playSegment(0.0, 0.5);">Play1</a>
<a href="javascript:playSegment(0.5);">Play2</a>

<script>
var audio = document.getElementById('sample');
var segmentEnd;

audio.addEventListener('timeupdate', function (){
    if (segmentEnd && audio.currentTime >= segmentEnd) {
        audio.pause();
    }
    console.log(audio.currentTime);
}, false);

function playSegment(startTime, endTime){
    segmentEnd = endTime;
    audio.currentTime = startTime;
    audio.play();
}
</script>

这篇关于HTML5音频:如何只播放音频文件的选定部分(音频精灵)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 23:14