我想通過向我的Node/Express服務器發出請求,將音頻文件從S3傳輸到我的React客戶端。我設法實現了一些可行的方法,但我不確定我是否真的在這裏流式傳輸這個文件,或者直接下載它。我懷疑我可能會下載文件,因爲我對服務器的請求需要很長的時間回來:通過Express服務器從S3流式傳輸音頻需要太長時間
Established database connection.
Server listening on port 9000!
::1 - - [18/Apr/2017:21:13:43 +0000] "GET/HTTP/1.1" 200 424 6.933 ms
::1 - - [18/Apr/2017:21:13:43 +0000] "GET /static/js/main.700ba5c4.js HTTP/1.1" 200 217574 1.730 ms
::1 - - [18/Apr/2017:21:13:43 +0000] "GET /index.css HTTP/1.1" 200 - 8.722 ms
Server received a request: GET /tracks
::1 - - [18/Apr/2017:21:13:43 +0000] "GET /tracks HTTP/1.1" 304 - 41.468 ms
Server received a request: GET /tracks/1/stream
::1 - - [18/Apr/2017:21:14:13 +0000] "GET /tracks/1/stream HTTP/1.1" 200 - 636.249 ms
Server received a request: GET /tracks/2/stream
Database query threw an error: ETIMEDOUT
注意636.249毫秒!
你們能否告訴我在這裏做錯了什麼?我粘貼下面我目前的方法的代碼;它具有以下功能:
- 客戶端發出一個fetch調用到
/tracks/id/stream
- 服務器查詢數據庫來獲取軌道
- Server使用
downloadStream
(從s3 package)來獲取文件 - 服務器管道數據到客戶端
- 客戶端接收數據作爲ArrayBuffer
- 客戶端解碼緩衝區並將其傳遞到AudioBufferSourceNode
- AudioBufferSourceNode播放音頻
服務器端:
app.get('/tracks/:id/stream', (req, res) => {
const id = req.params.id
// Query the database for all tracks
database.query(`SELECT * FROM Tracks WHERE id = ${id}`, (error, results, fields) => {
// Upon failure...
if (error) {
res.sendStatus(500)
}
// Upon success...
const params = {
Bucket: bucketName, // use bucketName defined elsewhere
Key: results[0].key // use the key from the track object
};
// Download stream and pipe to client
const stream = client.downloadStream(params)
stream.pipe(res)
})
});
客戶端獲取撥打:
const URL = `/tracks/${id}/stream`
const options = { method: 'GET' }
fetch(URL, options)
.then(response => response.arrayBuffer())
.then(data => {
// do some stuff
AudioPlayer.play(data)
})
客戶端AudioPlayer,負責處理實際AudioBufferSourceNode :
const AudioPlayer = {
play: function(data) {
// Decode the audio data
context.decodeAudioData(data, buffer => {
// Create a new buffer source
source = context.createBufferSource()
source.buffer = buffer
source.connect(context.destination)
// Start playing immediately
source.start(context.currentTime)
})
},
...
什麼是'client'和'downloadStream()' – peteb
我提到'downloadStream'來自[S3包(https://www.npmjs.com/package/s3);客戶也來自那裏。 – Gundam194