指定<audio>中的src =“”是没有.mp3扩展名的mp3文件?</audio>

时间:2013-03-06 18:10:08

标签: javascript jquery html5 jquery-plugins html5-audio

我需要一种方法来指定像

这样的东西
<audio src="http://somesite.com/track/377374"></audio>

有一个mp3文件作为来源。我无法在url的末尾使用.mp3扩展名,所以我需要其他方法来实现这一点。我正在使用自定义播放器jQuery插件,如果它无法确定音频标签中指定的文件格式,则会回退到旧的浏览器版本。我有办法实现这个目标吗?

3 个答案:

答案 0 :(得分:3)

您可以嵌套src="..."元素,而不是使用<source>。这将让你指出MIME类型。

对于你的例子:

<audio>
  <source src="http://somesite.com/track/377374" type="audio/mpeg3" />
</audio>

(免责声明:我没有测试过这是否得到了广泛的支持,或者它是否真的解决了你的jQuery插件所带来的问题。我只是基于the MDN documentation。)

答案 1 :(得分:3)

有一个功能可以检查文件扩展名并尝试匹配

    canPlayType   = function( file )
    {
        var audioElement = document.createElement( 'audio' );
        return !!( audioElement.canPlayType && 
                   audioElement.canPlayType( 'audio/' + file.split( '.' ).pop().toLowerCase() + ';' ).replace( /no/, '' ) );
    };

如果让我们说这个函数是返回true或者改为类似:

    canPlayType   = function( type )// type = mp3
    {
        var audioElement = document.createElement( 'audio' );
        return !!( audioElement.canPlayType && 
                   audioElement.canPlayType( 'audio/' + type.toLowerCase() + ';' ).replace( /no/, '' ) );
    };

然后插件行75的更新代码将假设文件是​​mp3并且在使用src时这样做...源元素仍然可以以传统方式使用。

else if( canPlayType( 'mp3' ) ) isSupport = true; // here change this

对于要检测的源类型(如@ruakh建议的那样,代码需要再次编辑:

if( typeof audioFile === 'undefined' )
{
    $this.find( 'source' ).each( function()
    {
        audioFile = $( this ).attr( 'src' );
        var sourceType = $( this ).attr( 'type' );
        if( typeof audioFile !== 'undefined' && 
                        typeof sourceType !== 'undefined' && 
                        canPlayType( sourceType.split( '/' ).pop().toLowerCase()  ) )
        {
            isSupport = true;
            return false;
        }
    });
}

答案 2 :(得分:0)

这是我第一个尝试在这里发挥创意的想法,如果您只需要在最后使用.mp3而不破坏指向页面的链接,您可以使用哈希标记的查询字符串,如

如果你可以修改网址,那么<audio src="http://somesite.com/track/377374?i=.mp3"></audio>会绕过插件,但仍允许你使用你的网址,而不是特定于文件类型。

但是当然如果你不想在最后显示.mp3,那么放弃这个想法。