-
Notifications
You must be signed in to change notification settings - Fork 17
/
useAudio.js
111 lines (94 loc) · 2.73 KB
/
useAudio.js
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
106
107
108
109
110
111
import React, { useState, useEffect, useRef } from "react";
import { useIPFS } from "./useIPFS";
const useAudio = (url) => {
const {resolveLink} = useIPFS();
const [audio, setAudio] = useState(url);
const [trackIndex, setTrackIndex] = useState(0);
const [newSong, setNewSong] = useState(0);
const [trackProgress, setTrackProgress] = useState(0);
const [isPlaying, setIsPlaying] = useState(false);
const [volume, setVolume] = useState(1);
const audioRef = useRef(new Audio(resolveLink(JSON.parse(audio[trackIndex].metadata).animation_url)));
const intervalRef = useRef();
const isReady = useRef(false);
const { duration } = audioRef.current;
const toPrevTrack = () => {
if (trackIndex - 1 < 0) {
setTrackIndex(audio.length - 1);
} else {
setTrackIndex(trackIndex - 1);
}
};
const toNextTrack = () => {
if (trackIndex < audio.length - 1) {
setTrackIndex(trackIndex + 1);
} else {
setTrackIndex(0);
}
};
useEffect(() => {
toggle();
setAudio(url);
if(trackIndex === 0){
setNewSong(newSong+1)
}else{
setTrackIndex(0);
}
}, [url]);
useEffect(() => {
if (isPlaying) {
audioRef.current.play();
startTimer();
} else {
clearInterval(intervalRef.current);
audioRef.current.pause();
}
}, [isPlaying]);
useEffect(() => {
return () => {
audioRef.current.pause();
clearInterval(intervalRef.current);
};
}, []);
useEffect(() => {
audioRef.current.pause();
audioRef.current = new Audio(resolveLink(JSON.parse(audio[trackIndex].metadata).animation_url));
audioRef.current.volume = volume;
setTrackProgress(Math.round(audioRef.current.currentTime));
if (isReady.current) {
audioRef.current.play();
setIsPlaying(true);
startTimer();
} else {
isReady.current = true;
}
}, [trackIndex, newSong]);
const toggle = () => setIsPlaying(!isPlaying);
const startTimer = () => {
clearInterval(intervalRef.current);
intervalRef.current = setInterval(() => {
if (audioRef.current.ended) {
toNextTrack();
} else {
setTrackProgress(Math.round(audioRef.current.currentTime));
}
}, [1000]);
};
const onSearch = (value) => {
clearInterval(intervalRef.current);
audioRef.current.currentTime = value;
setTrackProgress(audioRef.current.currentTime);
}
const onSearchEnd = () => {
if (!isPlaying) {
setIsPlaying(true);
}
startTimer();
}
const onVolume = (vol) => {
setVolume(vol);
audioRef.current.volume = vol;
};
return [isPlaying, duration,toggle, toNextTrack, toPrevTrack, trackProgress, onSearch, onSearchEnd, onVolume, trackIndex];
};
export default useAudio;