Add support for multiple types of audio (#1366)

This commit is contained in:
toasted-nutbread 2021-02-10 19:18:28 -05:00 committed by GitHub
parent 673952e825
commit 07cd006127
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 40 additions and 4 deletions

View File

@ -252,7 +252,9 @@ class AudioDownloader {
throw new Error('Could not retrieve audio'); throw new Error('Could not retrieve audio');
} }
return this._arrayBufferToBase64(arrayBuffer); const data = this._arrayBufferToBase64(arrayBuffer);
const contentType = response.headers.get('Content-Type');
return {data, contentType};
} }
async _isAudioBinaryValid(arrayBuffer, source) { async _isAudioBinaryValid(arrayBuffer, source) {

View File

@ -1604,8 +1604,9 @@ class Backend {
const {sources, customSourceUrl, customSourceType} = details; const {sources, customSourceUrl, customSourceType} = details;
let data; let data;
let contentType;
try { try {
data = await this._downloadDefinitionAudio( ({data, contentType} = await this._downloadDefinitionAudio(
sources, sources,
expression, expression,
reading, reading,
@ -1616,13 +1617,15 @@ class Backend {
binary: true, binary: true,
disableCache: true disableCache: true
} }
); ));
} catch (e) { } catch (e) {
// No audio // No audio
return null; return null;
} }
let fileName = this._generateAnkiNoteMediaFileName('yomichan_audio', '.mp3', timestamp, definitionDetails); let extension = this._mediaUtility.getFileExtensionFromAudioMediaType(contentType);
if (extension === null) { extension = '.mp3'; }
let fileName = this._generateAnkiNoteMediaFileName('yomichan_audio', extension, timestamp, definitionDetails);
fileName = fileName.replace(/\]/g, ''); fileName = fileName.replace(/\]/g, '');
await ankiConnect.storeMediaFile(fileName, data); await ankiConnect.storeMediaFile(fileName, data);

View File

@ -98,4 +98,35 @@ class MediaUtility {
return null; return null;
} }
} }
/**
* Gets the file extension for a corresponding media type.
* @param mediaType The media type to use.
* @returns A file extension including the dot for the media type,
* otherwise null.
*/
getFileExtensionFromAudioMediaType(mediaType) {
switch (mediaType) {
case 'audio/mpeg':
case 'audio/mp3':
return '.mp3';
case 'audio/mp4':
return '.mp4';
case 'audio/ogg':
case 'audio/vorbis':
return '.ogg';
case 'audio/vnd.wav':
case 'audio/wave':
case 'audio/wav':
case 'audio/x-wav':
case 'audio/x-pn-wav':
return '.wav';
case 'audio/flac':
return '.flac';
case 'audio/webm':
return '.webm';
default:
return null;
}
}
} }