html5音频设置currentTime

时间:2016-03-21 07:48:06

标签: javascript angularjs html5 spring-mvc html5-audio

我为HTML5制作了一个从我的服务器下载音乐的播放器,如果我从头开始播放歌曲,播放器工作得很好但是当我尝试使用currentTime属性从特定时间播放歌曲时没有任何事情发生,歌曲从开头开始

我的服务器端是Java spring mvc,我的客户端是angularJS。

提示部分:

音频工厂:

tunesApp.factory('audio', function($document) {
    var audio = $document[0].createElement('audio');
    return audio;
});

播放器工厂:

tunesApp.factory('player', function(audio, $rootScope) {
    var player,
        playlist = [],
        current = {
          track: 0
        };

    player = {
      playlist:playlist,
      play: function(track) {
        if (!playlist.length) return;

        if (angular.isDefined(track)) current.track = track;

        audio.src = playlist[current.track].url;
        audio.currentTime = playlist[current.track].startFrom; // also try with .toString()
        audio.play();
      }
    };

    playlist.add = function(album) {
      if (playlist.indexOf(album) != -1) return;
      playlist.push(album);
    };

    playlist.remove = function(album) {
      var index = playlist.indexOf(album);
      if (index == current.album) player.reset();
      playlist.splice(index, 1);
    };

    return player;
});

当我添加歌曲时:

tunesApp.controller('myController', function(player) {
    player.playlist.add({
        url: "/path/to/server",
        startFrom: 65 // in seconds
    });

    player.play();
});

和服务器控制器获取歌曲:

@RequestMapping(path="/song/{file_id}", method=RequestMethod.GET)
public void getFile(@PathVariable("file_id") String fileId, HttpServletResponse response){
    try{
        // get the song from the DB
        String songName = DB.getSong(fileId);
        File file = new File(fullPath + songName);
        response.setContentType("audio/mpeg"); // i use only mp3 files
        Long length = file.length();
        response.addHeader("Content-Range", "bytes 0-" + new Long(length-1).toString()+"/"+length);
        response.setContentLength((int)length);
        InputStream inputStream = new BufferInputStream(new FileInputStream(file));
        FileCopyUtils.copy(inputStream,response.getOutputStream());

        response.flushBuffer();
    }catch(Exception ex){}
}

这段代码工作了一段时间然后停止工作:(

更新

代码在边缘完美运行,但错误在chrome 44和48

任何帮助?

1 个答案:

答案 0 :(得分:0)

您可能需要等待" canPlay"在尝试改变时间之前要开火的事件。

借助Chrome桌面和Firefox,您还可以收听“已加载”的内容。事件,告诉您文件是否已加载到您正在寻找的点。