Код: Выделить всё
import React from 'react'
import { StyleSheet } from 'react-native'
import { Text } from 'react-native-paper'
import { TouchableOpacity, View } from 'react-native'
import { useState } from 'react/cjs/react.development'
import { useEffect } from 'react/cjs/react.development'
import { RandomSound } from '../../functions/sound'//function I made to select a random sound
import { LoadPlay_Sound } from '../../functions/sound'//function I made to load sounds
import { SmallCustomButton } from '../../functions/functions'//Custom button I made
const FourthFifth = () => {
const [answer,setanswer] = useState();
const [oringalanswer,setoriginalanswer] = useState();
const [sound,setsound] = useState([]);
const [currentsound,setcurrentsound] = useState();
const [changesound,setchangesound] = useState();
const [once,setonce] = useState(0);
const [played,setplayed] = useState(0);
const [correct,setcorrect] = useState(0);
//Loading all the intervals needed
useEffect(() => {
async function load() {
Promise.all([LoadPlay_Sound("perfectfourth"),LoadPlay_Sound("perfectfifth")])
.then(([perfectfourth,perfectfifth])=>{
setsound({perfectfourth:perfectfourth,perfectfifth:perfectfifth})
})
.catch(error=>{
console.log("An error occured while fetching sounds: "+error)
})
}
load();
}, []);
//Selecting a random interval when Sound state is filled or if changesound value is changed
useEffect(()=>{
async function setdata() {
RandomSound(sound)
.then((currentvalue)=>setcurrentsound(currentvalue))
.catch(error=>console.log("An error occured during Random selection: "+error))
}
if(Object.keys(sound).length>0)
{
setdata()
}
},[sound,changesound])
//Getting the key of that sound to check wheather the answer is correct.
//Runs when current sound is changed
useEffect(()=>{
async function Getkey() {
for (let key in sound) {
for(let soundobject of sound[key]){
if (soundobject === currentsound) {
setoriginalanswer(key=="perfectfourth"?"Perfect Fourth":"Perfect Fifth")
break;
}
}
}
}
if(Object.keys(sound).length>0)
{
Getkey()
}
},[currentsound])
//When I click on the button to play sound and if i click i again it stops playing
//And it also checks wheather I've pushed it by setting the Setplayed variable
async function handleplaysound(){
if (currentsound){
console.log(currentsound+" this is the sound")
LoadPlay_Sound(currentsound,"play")
.then(()=>{console.log(" Sound played successfully");setplayed(1)})
.catch(error=>console.log("Error occured while playing sound "+error))
}
else{
console.log("CurrentSound is not available")
}
}
//when I click on any of the options
function selectedchoice(choice){
//If answer is correct.
//Checks if I've already clicked another option and if I've clicked on the hear button
if(choice===oringalanswer && once==0 && played==1)
{
setanswer("Correct. Click to continue")
setcorrect(1);
setonce(1)
}
//If answer is wrong
//Checks if I've already clicked another option and if I've clicked on the hear button
else if(choice!==oringalanswer && once==0 && played==1)
{
setanswer("Wrong answer. It was "+ oringalanswer+"\nClick to continue.")
setcorrect(2);
setonce(1)
}
//If I haven't played the button to hear the sound atleast once
else if(played==0)
{
setplayed(2)
}
}
//When I click on the text. It resets all the State values and changes the current sound to new sound
function tonext()
{
if(correct==1 || correct==2)
{
setchangesound(Math.random()*10)
setanswer("")
setonce(0)
setplayed(0)
setcorrect(0)
}
}
//Styles for the buttons and view
const styles = StyleSheet.create({
container2:{
flexDirection:"row",
margin:10,
},
circle:{
marginBottom:100,
width:220,
height:220,
backgroundColor:"#A9E4F4",
borderRadius:100,
borderWidth:played==2?3:1,
borderColor:played==2?"#E67274":"black",
justifyContent: 'center',
shadowOpacity: 0.5,
shadowRadius: 16,
elevation: 25,
},
textstyle:{
fontSize:20,
textAlign:"center",
}
})
return(
Play Interval
selectedchoice("Perfect Fourth")} marginright={50} color={"#7DC345"} size={[10,15]} name="Perfect Fourth"/>
selectedchoice("Perfect Fifth")} color={"#7DC345"} size={[10,15]} name="Perfect Fifth"/>
tonext()} style={{fontWeight:"bold", position:"absolute", top:"57.5%", fontSize:15, color:"#E44346", textAlign:"center"}}>{answer}
)
}
export default FourthFifth

Код: Выделить всё
async function handleplaysound(){
if (currentsound){
console.log(currentsound+" this is the sound")
LoadPlay_Sound(currentsound,"play")
.then(()=>{console.log(" Sound played successfully");setplayed(1)})
.catch(error=>console.log("Error occured while playing sound "+error))
}
else{
console.log("CurrentSound is not available")
}
}
Код: Выделить всё
function tonext()
{
if(correct==1 || correct==2)
{
setchangesound(Math.random()*10)
setanswer("")
setonce(0)
setplayed(0)
setcorrect(0)
}
}
Приведенный ниже код представляет собой файл sound.js, из которого я импортирую «LoadPlay_Sound» и «RandomSound».
Код: Выделить всё
import {Audio} from 'expo-av'
const LoadPlay_Sound = async (file,play) => {
async function createaudio(avobject)
{
const soundobject = new Audio.Sound();
try {
await soundobject.loadAsync(avobject);
return soundobject;
} catch (error) {
console.log("Error occured while creating sound object in Sound.js: "+error)
}
}
if(file=="minorsecond")
{
try{
const audios = await Promise.all([
createaudio(require("../sounds/MinorSecond/MinorSecond-1.wav")),
createaudio(require("../sounds/MinorSecond/MinorSecond-2.wav")),
createaudio(require("../sounds/MinorSecond/MinorSecond-3.wav")),
createaudio(require("../sounds/MinorSecond/MinorSecond-4.wav")),
createaudio(require("../sounds/MinorSecond/MinorSecond-5.wav"))
])
return audios;
} catch (error) {
console.log("Error occured while fetching MinorSecond in Sound.js: "+error)
}
}
else if(file=="majorsecond")
{
try{
const audios = await Promise.all([
createaudio(require("../sounds/MajorSecond/MajorSecond-1.wav")),
createaudio(require("../sounds/MajorSecond/MajorSecond-2.wav")),
createaudio(require("../sounds/MajorSecond/MajorSecond-3.wav")),
createaudio(require("../sounds/MajorSecond/MajorSecond-4.wav")),
createaudio(require("../sounds/MajorSecond/MajorSecond-5.wav"))
])
return audios;
} catch (error) {
console.log("Error occured while fetching MajorSecond in Sound.js: "+error)
}
}
else if(file=="minorthird")
{
try {
const audios = await Promise.all([
createaudio(require("../sounds/MinorThird/MinorThird-1.wav")),
createaudio(require("../sounds/MinorThird/MinorThird-2.wav")),
createaudio(require("../sounds/MinorThird/MinorThird-3.wav")),
createaudio(require("../sounds/MinorThird/MinorThird-4.wav")),
createaudio(require("../sounds/MinorThird/MinorThird-5.wav"))
])
return audios
} catch (error) {
console.log("Error occured while fetching MinorThird in Sound.js: "+error)
}
}
else if(file=="majorthird")
{
try{
const audios = await Promise.all([
createaudio(require("../sounds/MajorThird/MajorThird-1.wav")),
createaudio(require("../sounds/MajorThird/MajorThird-2.wav")),
createaudio(require("../sounds/MajorThird/MajorThird-3.wav")),
createaudio(require("../sounds/MajorThird/MajorThird-4.wav")),
createaudio(require("../sounds/MajorThird/MajorThird-5.wav"))
])
return audios;
} catch (error) {
console.log("Error occured while fetching MajorThird in Sound.js: "+error)
}
}
else if(file=="perfectfourth")
{
try{
const audios = await Promise.all([
createaudio(require("../sounds/PerfectFourth/PerfectFourth-1.wav")),
createaudio(require("../sounds/PerfectFourth/PerfectFourth-2.wav")),
createaudio(require("../sounds/PerfectFourth/PerfectFourth-3.wav")),
createaudio(require("../sounds/PerfectFourth/PerfectFourth-4.wav")),
createaudio(require("../sounds/PerfectFourth/PerfectFourth-5.wav"))
])
return audios;
} catch (error) {
console.log("Error occured while fetching PerfectFourth in Sound.js: "+error)
}
}
else if(file=="perfectfifth")
{
try{
const audios = await Promise.all([
createaudio(require("../sounds/PerfectFifth/PerfectFifth-1.wav")),
createaudio(require("../sounds/PerfectFifth/PerfectFifth-2.wav")),
createaudio(require("../sounds/PerfectFifth/PerfectFifth-3.wav")),
createaudio(require("../sounds/PerfectFifth/PerfectFifth-4.wav")),
createaudio(require("../sounds/PerfectFifth/PerfectFifth-5.wav"))
])
return audios;
} catch (error) {
console.log("Error occured while fetching PerfectFifth in Sound.js: "+error)
}
}
else if(file=="minorsixth")
{
try{
const audios = await Promise.all([
createaudio(require("../sounds/MinorSixth/MinorSixth-1.wav")),
createaudio(require("../sounds/MinorSixth/MinorSixth-2.wav")),
createaudio(require("../sounds/MinorSixth/MinorSixth-3.wav")),
createaudio(require("../sounds/MinorSixth/MinorSixth-4.wav")),
createaudio(require("../sounds/MinorSixth/MinorSixth-5.wav"))
])
return audios;
} catch (error) {
console.log("Error occured while fetching MinorSixth in Sound.js: "+error)
}
}
else if(file=="majorsixth")
{
try{
const audios = await Promise.all([
createaudio(require("../sounds/MajorSixth/MajorSixth-1.wav")),
createaudio(require("../sounds/MajorSixth/MajorSixth-2.wav")),
createaudio(require("../sounds/MajorSixth/MajorSixth-3.wav")),
createaudio(require("../sounds/MajorSixth/MajorSixth-4.wav")),
createaudio(require("../sounds/MajorSixth/MajorSixth-5.wav"))
])
return audios;
} catch (error) {
console.log("Error occured while fetching MajorSixth in Sound.js: "+error)
}
}
else if(file=="minorseventh")
{
try{
const audios = await Promise.all([
createaudio(require("../sounds/MinorSeventh/MinorSeventh-1.wav")),
createaudio(require("../sounds/MinorSeventh/MinorSeventh-2.wav")),
createaudio(require("../sounds/MinorSeventh/MinorSeventh-3.wav")),
createaudio(require("../sounds/MinorSeventh/MinorSeventh-4.wav")),
createaudio(require("../sounds/MinorSeventh/MinorSeventh-5.wav"))
])
return audios;
} catch (error) {
console.log("Error occured while fetching MinorSeventh in Sound.js: "+error)
}
}
else if(file=="majorseventh")
{
try{
const audios = await Promise.all([
createaudio(require("../sounds/MajorSeventh/MajorSeventh-1.wav")),
createaudio(require("../sounds/MajorSeventh/MajorSeventh-2.wav")),
createaudio(require("../sounds/MajorSeventh/MajorSeventh-3.wav")),
createaudio(require("../sounds/MajorSeventh/MajorSeventh-4.wav")),
createaudio(require("../sounds/MajorSeventh/MajorSeventh-5.wav"))
])
return audios;
} catch (error) {
console.log("Error occured while fetching MajorSeventh in Sound.js: "+error)
}
}
else if(file=="octave")
{
try{
const audios = await Promise.all([
createaudio(require("../sounds/Octave/Octave-1.wav")),
createaudio(require("../sounds/Octave/Octave-2.wav")),
createaudio(require("../sounds/Octave/Octave-3.wav")),
createaudio(require("../sounds/Octave/Octave-4.wav")),
createaudio(require("../sounds/Octave/Octave-5.wav"))
])
return audios;
} catch (error) {
console.log("Error occured while fetching Octave in Sound.js: "+error)
}
}
else if(play=="play")
{
try{
await file.playAsync();
}
catch(error){
console.log("Error occured while playing the sound in Sound.js: "+error)
}
}
else if(play=="stop")
{
try{
await file.stopAsync();
}
catch(error){
console.log("Error occured while stoping the sound in Sound.js: "+error)
}
}
}
const RandomSound = async (soundobject) => {
try {
const dictkey = Object.keys(soundobject)
const index = Math.floor(Math.random()*dictkey.length)
let value = dictkey[index]
value = soundobject[value]
const index2 = Math.floor(Math.random(value)*value.length)
return value[index2];
} catch (error) {
console.log("Error while selecting a random sound object in Sound.js: "+error)
}
}
export {RandomSound, LoadPlay_Sound}
В приведенном ниже коде я попробовал зарегистрировать проблему:
Код: Выделить всё
//In the interface file
async function handleplaysound(){
if (currentsound){
console.log(currentsound+" this is the sound")
LoadPlay_Sound(currentsound,"play")
.then(()=>{console.log(" Sound played successfully");setplayed(1)})
.catch(error=>console.log("Error occured while playing sound "+error))
}
else{
console.log("CurrentSound is not available")
}
}
//In the sound.js file
else if(play=="play")
{
try{
await file.playAsync();
}
catch(error){
console.log("Error occured while playing the sound in Sound.js: "+error)
}
}
LOG [Объект объекта] это звук. LOG Ошибка при воспроизведении звука в Sound.js: Ошибка: проигрыватель не существует.
LOG Звук воспроизведен успешно
И в большинстве случаев ошибок не возникает, но звук просто не воспроизводится. как я уже сказал, он играет только в первый раз, а потом нет. Тогда LOG будет выглядеть так:
LOG [объект Объект] это звук
LOG Звук успешно воспроизведен
Кроме того, когда я открываю свой проект в браузере, он работает нормально. Упомянутая проблема возникает только тогда, когда я открываю ее на своем телефоне с помощью QR-кода Expo. Ниже я предоставил подробное видеообъяснение проблемы.
Вот как это работает в браузере: https://youtube.com/shorts/ZHsYHXcJXYA?feature=share
Вот как это работает на мобильном устройстве: https://youtube.com/shorts/9zUjd2mzTD0?feature=share
Спасибо.
Подробнее здесь: https://stackoverflow.com/questions/785 ... ot-playing