我试图在使用expo-cli创建的本地应用程序中播放一些音频。
代码用typescript编写,违规代码如下所示,取自expo.io documentation:
import * as React from 'react'
import { WorkoutComponent } from "./WorkoutExecutor";
import { Audio } from 'expo';
export default class AudioPlayer {
private async playAudio(fileName: string) {
console.log("Playing Audio: " + fileName);
const soundFile = './assets/sounds/' + fileName + '.mp3';
try {
const { sound: soundObject, status } = await Audio.Sound.createAsync(
require(soundFile),
{ shouldPlay: true }
);
// Your sound is playing!
} catch (error) {
console.log(error);
// An error occurred!
}
}
[...]
}
当应用程序加载时,它会出现以下错误,甚至在它到达屏幕时会发出声音
[...]\src\AudioPlayer.ts:Invalid call at line 13: require(soundFile)
我意识到这个例子是用javascript而不是打字稿,但是我错过了什么?
我的tsconfig.json是expo typescript示例中的一个,看起来像这样
{
"compilerOptions": {
"baseUrl": "./src",
"esModuleInterop": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"importHelpers": true,
"jsx": "react-native",
"module": "es2015",
"moduleResolution": "node",
"noEmitHelpers": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
// Using the type definitions in @types/expo becuase they are still better than the ones provided by expo. See SvgScreen.tsx and SystemFontsScreen.tsx.
"paths": {
"expo": [
"../node_modules/@types/expo",
"../node_modules/expo"
],
},
"skipLibCheck": true,
"strict": true,
"target": "es2017"
},
"exclude": [
"node_modules"
]
}
我通过Twitter得到了帮助,问题是require()
无法使用动态值。这也解释了为什么错误发生在应用程序被加载之前,因为它试图在构建或加载时解析require
,而不是像我想象的那样在运行时解析。