0

使用chirp-js-sdkNext.js 不是问题,但由于我的应用程序需要接收chirp浏览器发送的数据,因此我不得不使用 WebAssembly SDK。我在哪里以及如何实例化和使用chirpsdk?

按照此处的说明进行设置,我没有遇到任何问题。但是,不会调用onReceived,回调。onReceiving

这是我正在使用的页面的片段chirpsdk

class AttendEvent extends Component {

    static async getInitialProps({req, query, res}) {
        return {
            attendString: query
        }
    }

    constructor() {
        super();
        this.sdk = null;
        this.state = {
            user: '',
            started: false,
            waiting: false,
            receiving: false,
            received: 'Awaiting messages..',
            disabled: false
        }
    }

    toAscii(payload) {
        let str = ''
        for (let i = 0; i < payload.length; i++) {
            str += String.fromCharCode(payload[i])
        }
        return str
    }

    async startSDK() {
        this.sdk = await import ('../node_modules/chirpsdk/index').then( ({Chirp}) => {
            return Chirp({
                key: CHIRP_API_KEY,
                onReceiving: () => {
                    console.log('Receving Data');
                    this.setState({
                        ...this.state,
                        received: '...',
                        disabled: true
                    })
                },
                onReceived: data => {
                    console.log("Received Data");
                    if (data.length > 0) {
                        this.setState({
                            ...this.state,
                            received: this.toAscii(data),
                            disabled: false
                        })
                    } else {
                        this.setState({
                            ...this.state,
                            received: `I didn't hear that. Try turning the volume up?`,
                            disabled: false
                        })
                    }
                }
            })
        })
        this.setState({ 
            ...this.state,
            started: true 
        })
    }

    componentDidMount() {
        loadFirebase().auth().onAuthStateChanged(user => {
            if (user) {
                this.setState({
                    ...this.state,
                    user: user
                })
                return user
                    .getIdToken()
                    .then(token => {
                        return fetch('/api/login', {
                            method: 'POST',
                            headers: new Headers({ 'Content-Type': 'application/json' }),
                            credentials: 'same-origin',
                            body: JSON.stringify({ token })
                        })
                    })
            } else {
                Router.push('/');
            }
        })

        this.setState({
            ...this.state,
            waiting: true
        })

    }

    handleLogout() {
        loadFirebase().auth().signOut()
    }

    render() {
        const { classes } = this.props;
        return (
            <React.Fragment>
                <Navbar page="AttendEvent" />
                {
                    this.state.user !== null ? (
                        <Grid
                            container
                            spacing={0}
                            direction="row"
                            alignItems="center"
                            justify="center"
                            style={{ minHeight: '90vh' }}
                        >
                            <Typography variant="h1">
                                {
                                    this.state.waiting ? "Waiting for code..." : (this.state.receiving ? "Receiving code...": (this.state.received ? this.state.received : "Mounting...") )
                                }
                            </Typography> <br/>
                            <Button variant="contained" color="primary" onClick={() => {
                                this.startSDK()
                            }}>
                                START
                            </Button>
                        </Grid>) : true
                }
            </React.Fragment>);
    }
}

我希望onReceived在接收16kHz-mono音频消息时调用回调,但它没有被调用。

4

1 回答 1

1

找到了我自己的问题的解决方案,这似乎运作良好。

问题在于动态导入和处理承诺的方式。

async startSDK() {
        this.sdk = await import ('../node_modules/chirpsdk/index')
        .then(({Chirp}) => {
            return Chirp ({
               // rest of the initialisation parameters
            })
         )
        .catch( error => {
           console.log(error.message);
         }

         this.setState({
                ...this.state,
                started: true
         })
}

它应该做的方式。虽然,这也可以完成then..catch

async startSDK(){
       try {
          const chirp = await import('../node_modules/chirpsdk/index');
          const { Chirp } = chirp;
          this.sdk = await Chirp ({
             // rest of the initialisation parameters
          )}
       } 
       catch (err) {
          console.log(err);
       }
       this.setState({
                ...this.state,
                started: true
       })
}

关于为什么使用动态导入的旁注

最初,我认为 Next.js 会chirpsdk像 React 一样处理导入。但是,我想由于 Next 的 SSR 特性,导入无法按预期工作,这是抛出的错误:

Assertion failed: undefined
Assertion failed: undefined
abort("Assertion failed: undefined") at Error
    at /Users/warrenwhite/Documents/MajorProj/faculty-dashboard-app-ssr/node_modules/chirpsdk/index.js:1:10515
    at z (/Users/warrenwhite/Documents/MajorProj/faculty-dashboard-app-ssr/node_modules/chirpsdk/index.js:1:10647)
    at sn (/Users/warrenwhite/Documents/MajorProj/faculty-dashboard-app-ssr/node_modules/chirpsdk/index.js:1:75732)
    at O (/Users/warrenwhite/Documents/MajorProj/faculty-dashboard-app-ssr/node_modules/chirpsdk/index.js:1:5568)
    at Ne (/Users/warrenwhite/Documents/MajorProj/faculty-dashboard-app-ssr/node_modules/chirpsdk/index.js:1:14094)
    at /Users/warrenwhite/Documents/MajorProj/faculty-dashboard-app-ssr/node_modules/chirpsdk/index.js:1:22110
    at Object.openDatabase (/Users/warrenwhite/Documents/MajorProj/faculty-dashboard-app-ssr/node_modules/chirpsdk/index.js:1:21497)
    at Object.staticInit (/Users/warrenwhite/Documents/MajorProj/faculty-dashboard-app-ssr/node_modules/chirpsdk/index.js:1:21983)
    at /Users/warrenwhite/Documents/MajorProj/faculty-dashboard-app-ssr/node_modules/chirpsdk/index.js:1:27857
    at E.locateFile (/Users/warrenwhite/Documents/MajorProj/faculty-dashboard-app-ssr/node_modules/chirpsdk/index.js:1:131)
    at Object.<anonymous> (/Users/warrenwhite/Documents/MajorProj/faculty-dashboard-app-ssr/node_modules/chirpsdk/index.js:1:226)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
于 2019-03-26T06:49:04.013 回答