先放一個效果圖:該圖實現的效果,點擊播放按鈕,進度條隨着時間移動,點擊暫停按鈕,進度條停止移動
第一步,用到什么庫
1.zmxv/react-native-sound 播放聲音的庫
2.callstack/react-native-slider 進度條的庫
第二步,准備播放音頻
我測試時,是將mp3格式的聲音放在本地的,根據官網描述,本地音頻,放在 `android\app\src\main\res\raw`,注意要重新編譯打包項目哦
import React from "react"; import { View, Text, StyleSheet } from 'react-native';
import Sound from "react-native-sound"; Sound.setCategory('Playback'); class SoundScreen extends React.Component { constructor(props) { super(props); this.state = { whoosh: null, //音頻對象 } } componentDidMount() {
//構建好音頻對象 this.build(); } build(){ let audioSrc = 'whoosh.mp3' //這個音頻放在android\app\src\main\res\raw let whoosh = new Sound(audioSrc, Sound.MAIN_BUNDLE, (error) => { if (error) { alert('加載聲音失敗'); return; } this.setState({ whoosh: whoosh}); }); }
playAudio=()=>{
this.state.whoosh.play((success) => { if (success) {//播放完成后的邏輯在這里處理 } else { console.log('playback failed due to audio decoding errors'); } }); }
render(){
return (
<Text onPress={this.playAudio}>播放</Text>
)
} }
第三步,添加Slider滑塊組件
自己看文檔添加吧,這里有個小問題,就是設置長度300,但是它左右兩邊有8個距離的空襲,我也沒解決
第四步,mp3音頻播放時間 和 Slider進度同步的問題
思路:Slider的最小值為0 ,最大值為1 ,之后通過定時器,獲得當前播放時間 除以 總時長,這個值就是Slider的值
注意,將debug關掉,不然定時任務不准確
//定時任務:監聽當前播放時間
listenAudio() { let that = this; let timer = setInterval(function () { that.state.whoosh.getCurrentTime(function (seconds) { let duration = that.state.duration; let temp = seconds / duration;//當前時間/總時間 = 播放進度比
that.setState({ sliderValue: temp, }) }); }, 1000); //將定時器私有化
this.setState({ Timer: timer }); }
主要的內容都說完,注意清除定時器對象