gerson
2024-08-11 b2b8e5ed16f139597b10452df0c467b6e7cde500
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
const fillIn = val => `${val < 10 ? '0' : ''}${val}`,
    formatTime = _time => {
        let time = Math.round(_time);
        let second = Math.round(time % 60),
            minute = Math.floor(time / 60 % 60),
            hour = Math.floor(time / 60 / 60);
        return `${fillIn(hour)}:${fillIn(minute)}:${fillIn(second)}`;
    };
 
class Audio{
    constructor(obj){
        const _ts = this,
            option = _ts.option = obj.attrs;
 
        _ts.loop = option.loop === 'true',
        _ts.autoplay = option.autoplay === 'true';
        _ts.create();
        _ts.index = 0;
 
        
    }
    create(){
        const _ts = this,
            option = _ts.option;
        let audio = _ts.audio = wx.createInnerAudioContext();
        audio.src = option.src;
 
        // 说明可以播放了
        audio.onCanplay(function(){
            if(_ts.autoplay && !_ts.index){
                _ts.play();
            };
            if(!_ts.autoplay && !_ts.index){
                _ts.eventCanplay();
            };
        });
 
        // 更新时间
        audio.onTimeUpdate(function(){
            //_ts.status = 'update';
            _ts.duration = audio.duration;
            _ts.currentTime = audio.currentTime;
 
            // 定义播放结束
            if(_ts.duration - _ts.currentTime < 0.5){
                _ts.index++;
                if(_ts.loop){
                    audio.stop();
                }else{
                    _ts.stop();
                };
                audio.seek(0);
            };
            _ts.eventTimeUpdate(formatTime(_ts.duration),formatTime(_ts.currentTime));
        });
 
        // 
        audio.onSeeked(function(){
            if(_ts.loop){
                _ts.play();
            };
        });
 
 
 
    }
    // 播放
    play(){
        const _ts = this;
        _ts.status = 'play';
        _ts.audio.play();
        _ts.eventPlay();
    }
    // 暂停
    pause(){
        const _ts = this;
        _ts.status = 'pause';
        _ts.audio.pause();
        _ts.eventPause();
    }
    // 停止
    stop(){
        const _ts = this;
        _ts.status = 'stop';
        _ts.audio.stop();
        _ts.eventStop();
    }
    // 销毁
    destroy(){
        const _ts = this;
        _ts.stop();
        _ts.audio.destroy();
    }
    eventCanplay(){}
    eventTimeUpdate(){}
    eventEnded(){}
    eventError(){}
    eventPause(){}
    eventPlay(){}
    eventSeeked(){}
    eventSeeking(){}
    eventStop(){}
    eventWaiting(){}
};
module.exports = Audio;