在Safari中通过Blob URL加载音频失败 [英] Loading audio via a Blob URL fails in Safari

查看:441
本文介绍了在Safari中通过Blob URL加载音频失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在Chrome(22.0)中有效,但在Safari(6.0)中无效

Following code works in Chrome (22.0) but not in Safari (6.0)

<!DOCTYPE html>
<html>
<head>
<script>
function onGo(e) {
  var fr = new FileReader();
  var file = document.getElementById("file").files[0];
  fr.onload = function(e) {
      var data = new Uint8Array(e.target.result);
      var blob = new Blob([data], {type: 'audio/mpeg'});
      var audio = document.createElement('audio'); 
      audio.addEventListener('loadeddata', function(e) { 
          audio.play();
        }, false);
      audio.addEventListener('error', function(e) {
          console.log('error!', e);
        }, false);
      audio.src = webkitURL.createObjectURL(blob);    
    };
  fr.readAsArrayBuffer(file);
}
</script>
</head>
<body>
  <input type="file" id="file" name="file" />
  <input type="submit" id="go" onclick="onGo()" value="Go" />
</body>
</html>

在Safari中,不会调用回调(loadeddata或错误). 使用的内容是mp3文件,通常会使用音频标签播放. Safari是否需要任何特殊护理?

In Safari, neither callback (loadeddata nor error) is called. The content used is an mp3 file, which is normally played back with audio tag. Is there any special care needed for Safari?

推荐答案

很多年后,我相信OP中的示例应该可以正常工作.只要您在创建Blob时以某种方式设置了mime类型,就像上面的OP通过传入的选项的type属性来进行设置一样:

Many years later, I believe the example in the OP should work just fine. As long as you somehow set the mime type when creating the blob, like the OP does above with the type property of the options passed in:

new Blob([data], {type: 'audio/mpeg'});

您还可以在音频元素内部使用<source>元素,并设置<source>元素的type属性.我在这里有一个示例:

You could also use a <source> element inside of an audio element and set the type attribute of the <source> element. I have an example of this here:

https://lastmjs.github.io/safari-object-url-test

这是代码:

const response = await window.fetch('https://upload.wikimedia.org/wikipedia/commons/transcoded/a/ab/Alexander_Graham_Bell%27s_Voice.ogg/Alexander_Graham_Bell%27s_Voice.ogg.mp3');

const audioArrayBuffer = await response.arrayBuffer();
const audioBlob = new Blob([audioArrayBuffer]);
const audioObjectURL = window.URL.createObjectURL(audioBlob);

const audioElement = document.createElement('audio');

audioElement.setAttribute('controls', true);
document.body.appendChild(audioElement);

const sourceElement = document.createElement('source');

audioElement.appendChild(sourceElement);

sourceElement.src = audioObjectURL;
sourceElement.type = 'audio/mp3';

我更喜欢在创建Blob时设置其mime类型. <source>元素src的属性/属性无法动态更新.

I prefer just setting the mime type of the blob when creating it. The <source> element src attribute/property cannot be updated dynamically.

这篇关于在Safari中通过Blob URL加载音频失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆