当前位置: 首页 > 工具软件 > React-Total > 使用案例 >

react-native-sound 音频

施同
2023-12-01

github:https://github.com/zmxv/react-native-sound

安装及添加依赖

npm install react-native-sound --save
或者
yarn add react-native-sound
react-native link react-native-sound

手动配置地址:https://github.com/zmxv/react-native-sound/wiki/Installation

实现代码

用到了react-native-elements 的Slider组件,可随意改变当前播放进度

播放网络音频:new Sound(url, null, err => {}) 

let url = 'https://languagezenstorage.blob.core.windows.net/media0/xgcUXjHhP8.mp3';
    let whoosh = new Sound(url, '', err => {
      if(err) {
        return console.log(err)
      }
      whoosh.play(success =>{
        if(success) {
          console.log('远程文件播放成功')
        }else {
          console.log('远程文件播放失败')
        }
      })
    })

 本地音频文件

import React, {Component} from 'react';
import { StyleSheet, Text, View } from 'react-native';

import { Slider } from 'react-native-elements'
import Sound from 'react-native-sound'

let mp3 = require('./sounds/guojing_xinqiang.mp3');//支持众多格式
//如果是网络音频,使用 new Sound(mp3,null,error => {})
let whoosh = new Sound(mp3, (error) => {
	if (error) {
		return console.log('资源加载失败', error);
	}
});

export default class mySound extends Component {
	constructor(props){
		super(props);
		this.state = {
			volume: 0.5,
			seconds: 0, //秒数
			totalMin: '', //总分钟
			totalSec: '', //总分钟秒数
			nowMin: 0, //当前分钟
			nowSec: 0, //当前秒钟
			maximumValue: 0, //滑块最大值
		}
	}
	componentDidMount(){
		let totalTime = whoosh.getDuration();
		totalTime = Math.ceil(totalTime);
		let totalMin = parseInt(totalTime/60); //总分钟数
		let totalSec = totalTime - totalMin * 60; //秒钟数并判断前缀是否 + '0'
		totalSec = totalSec > 9 ? totalSec : '0' + totalSec;
		this.setState({
			totalMin,
			totalSec,
			maximumValue: totalTime,
		})
	}
	componentWillUnmount(){
		this.time && clearTimeout(this.time);
	}
	// 声音+
	_addVolume = () => {
		let volume = this.state.volume;
		volume += 0.1;
		volume = parseFloat(volume).toFixed(1) * 1;
		if(volume > 1){
			return alert('目前已经是最大音量');
		}
		this.setState({volume: volume});
		whoosh.setVolume(volume);
	}
	// 声音-
	_reduceVolume = () => {
		let volume = this.state.volume;
		volume -= 0.1;
		volume = parseFloat(volume).toFixed(1) * 1;
		if(volume < 0){
			return alert('当前为静音');
		}
		this.setState({volume: volume});
		whoosh.setVolume(volume);
	}
	// 播放
	_play = () => {
		whoosh.play();
		this.time = setInterval(() => {
			whoosh.getCurrentTime(seconds => {
				seconds = Math.ceil(seconds);
				this._getNowTime(seconds)
			})
		},1000)
	}
	// 暂停
	_pause = () => {
		clearInterval(this.time);
		whoosh.pause();
	}
	// 停止
	_stop = () => {
		clearInterval(this.time);
		this.setState({
			nowMin: 0,
			nowSec: 0,
			seconds: 0,
		})
		whoosh.stop();
	}
	_getNowTime = (seconds) => {
		let nowMin = this.state.nowMin,
			nowSec = this.state.nowSec;
		if(seconds >= 60){
			nowMin = parseInt(seconds/60); //当前分钟数
			nowSec = seconds - nowMin * 60;
			nowSec = nowSec < 10 ? '0' + nowSec : nowSec;
		}else{
			nowSec = seconds < 10 ? '0' + seconds : seconds;
		}
		this.setState({
			nowMin,
			nowSec,
			seconds
		})
	}
    render() {
		let time = this.state;
        return (
			<View style={styles.container}>
				<Slider
                    // disabled //禁止滑动
                    maximumTrackTintColor={'#ccc'} //右侧轨道的颜色
                    minimumTrackTintColor={'skyblue'} //左侧轨道的颜色
                    maximumValue={this.state.maximumValue} //滑块最大值
					minimumValue={0} //滑块最小值
                    value={this.state.seconds}					
                    onSlidingComplete={(value)=>{ //用户完成更改值时调用的回调(例如,当滑块被释放时)
						value = parseInt(value);
						this._getNowTime(value)
						// 设置播放时间
						whoosh.setCurrentTime(value);
                    }}
                />
				<Text>{time.nowMin}:{time.nowSec}/{time.totalMin}:{time.totalSec}</Text>
				<Text>当前音量: {this.state.volume}</Text>
				<Text onPress={this._addVolume}>声音+</Text>
				<Text onPress={this._reduceVolume}>声音-</Text>
				<Text onPress={this._play}>播放</Text>
				<Text onPress={this._pause}>暂停</Text>
				<Text onPress={this._stop}>停止</Text>
			</View>
        );
    }
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#F5FCFF',
	},
});

 

 类似资料: