import request from 'umi-request'

const ac = new (window.AudioContext || (window as any).webkitAudioContext)()

export type IList = any[]

export default class Player {
  list:any []
  arrayBuffer: ArrayBuffer[] = []
  constructor (list:any []) {
    this.list = list
  }

  load() {
    const promises = this.list.map(item => request.get(item, {responseType: 'arrayBuffer'}))
    return Promise.all(promises)
      .then(res => this.arrayBuffer = res)
  }

  async play() {
    if (!this.arrayBuffer.length) {
      await this.load()
    }
    const decodedDatas = this.arrayBuffer.map(async item => {
      const data = await ac.decodeAudioData(item)
      return data
    })
    const sources = decodedDatas.map(async item => {
      const source = await ac.createBufferSource()
      source.buffer = await item
      source.connect(ac.destination)
      return source
    })
    for (const item of sources) {
      const source = await item
      source.playbackRate.value = 1.5
      source.start()
      console.log(source)
    }
    // await Promise.all(sources)
    // .then(res => await res)
    // console.log(sources)
  }
}
