[英]How to stop a sound when the stop button is clicked in snack expo?
我正在制作一個應用程序,它有一些播放不同聲音的按鈕,以及一個停止所有聲音的停止按鈕。 但是,它僅在當前聲音播放停止時才起作用,並且不播放任何其他音樂。 function 不正確嗎? 這是代碼(其他按鈕的編寫方式與第一個按鈕相同):
import React, { Component } from 'react';
import { Button, View, Text, Alert, TouchableOpacity } from 'react-native';
import {Audio} from "expo-av";
class Button1 extends React.Component {
playSound1 = async () => {
await Audio.Sound.createAsync(
{uri:"https://s1.yt.ninja/@download/23481-602b351bd79f3-10112020-252-320-file-10112020/mp3/lcVNSPXM2Nc/The%2BUntamed%2BOST%2B%257C%2B%25E9%2599%2588%25E6%2583%2585%25E4%25BB%25A4%2BMain%2BThemed%2BSong%25E3%2580%258A%25E6%2597%25A0%25E7%25BE%2581%2BWu%2BJi%25E3%2580%258B%25E2%2580%2594%25E2%2580%2594Xiao%2BZhan%2B%25E3%2580%2581Wang%2BYi%2BBo%2BDuet.mp3/9f05bbbdbd17b34a35bd40794186a567e755c50ee15ef6c77345bf1eaf7e8124-1"},
{shouldPlay:true}
)
}
render() {
return (
<TouchableOpacity style={{
backgroundColor : "#D1A5C9",
marginTop: 30,
marginLeft: 25,
width: 280,
height: 40,
alignItems: "center"
}}
onPress={this.playSound1}>
<Text style={{
color:"white",
fontSize: 30,
}}>Sound 1</Text>
</TouchableOpacity>
);
}
}
class StopButton extends React.Component{
render(){
return(
<TouchableOpacity style={{
backgroundColor : "black",
marginTop: 50,
marginLeft: 40,
width: 250,
height: 40,
alignItems: "center"
}}
onPress={() => {
Audio.setIsEnabledAsync(false)
}}>
<Text style={{
color:"white",
fontSize: 30,
}}>Stop Sound</Text>
</TouchableOpacity>
)
}
}
export default class App extends React.Component {
render() {
return (
<View>
<Button1/>
<Button2/>
<Button3/>
<Button4/>
<Button5/>
<StopButton/>
</View>
);
}
}
嘗試使用 Audio.Sound 的實例來停止音頻。
例如:
const {
sound: soundObject,
status,
} = await Audio.Sound.createAsync(require('./assets/sounds/hello.mp3'), { shouldPlay: true });
並在停止按鈕操作上處理 soundObject 以停止音樂:
onStop = async () => {
soundObject.stopAsync()
}
有關更多詳細信息,請查看 expo AV 的官方文檔
https://docs.expo.io/versions/latest/sdk/audio/#audiosetaudiomodeasyncmode
它可以工作,但只能在您的手機上工作,而不是模擬器或 web 選項
但是一旦你停止它,它就不會再開始聲音了,除非你添加這個
class SoundButton6 extends Component {
render() {
return (
<TouchableOpacity
style={{
backgroundColor: 'red',
marginLeft: 100,
borderWidth: 1,
borderColor: 'black',
alignItems: 'center',
justifyContent: 'center',
width: 200,
height: 100,
borderRadius: 100,
marginTop: 10,
}}
onPress={ () => {
Audio.setIsEnabledAsync(true);
}}>
<Text
style={{
fontWeight: 'bold',
fontSize: 35,
}}>
Resume
</Text>
</TouchableOpacity>
);
}
}
恢復按鈕
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.