请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

safari无法播放音乐

我是在每次currentSong变化时,先去异步请求歌曲url,然后绑定到audio的src属性,接着再去执行audio.play( ) . 为了保证请求完成之后再执行绑定,所以我用了promise.then方法,但是这样做safari播放不了,困扰两天了,请教一下应该怎么处理这个问题。
注:我是用的网易云音乐API,所以是每次currentSong变化时,再去根据获取歌曲url。

以下为代码:
dom部分:

<audio :src="songurl" ref="audio" @canplay="ready" @error="error" @timeupdate="updateTime"></audio>

这里的":src=songurl",我是在data里面初始化了一个’songurl’ :

        data() {
            return {
                songurl: '',
                songReady: false,
                currentTime: 0
            }
        },

watch部分:

        watch: {
            currentSong() {
                var v = this;
                v.getSongUrl(v.currentSong.id).then(() => {
                    v.$nextTick(() => {
                        v.$refs.audio.play();
                    });
                })
            },
            playing(newPlaying) {
                var v = this;
                const audio = v.$refs.audio;
                v.getSongUrl(v.currentSong.id).then(() => {
                    v.$nextTick(() => {
                       newPlaying ? audio.play() : audio.pause();
                    });
                })

            }
        },

可以看到,我是先去调用了v.getSongUrl( ) 这个方法去获取歌曲URL,这个promise执行完成之后,然后再去播放歌曲。
以下为getSongUrl( ) 方法:

            getSongUrl(id) {
                var v = this;
                return v.$axios.get('api/song/url', {
                    params: {
                        id: id
                    }
                }).then(response => {
                    if (response.data.code === 200) {
                        v.songurl = response.data.data[0].url;
                        //console.log("地址:" + v.songurl);
                    }
                }).catch(error => {
                    console.log(error);
                });

            },

所以就是,我先去异步请求,然后将获取的url赋值给data里面的songurl,然后绑定到audio的src上面,然后再去调用audio.play. 但是safari就是不能播放。

以下为safari报的错误:

Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

点击这个错误,就会定位到audio.play( )这里。
最后,这个问题已经困扰我很久了,查阅了老师的升级踩坑小记,看了很多的文档资料,试过了很多的方法,但是问题依旧没解决。还望老师给予帮助,小弟定当临表涕零,不胜感激!!?

正在回答

1回答

本质上你调用 audio.play 播放的时候就不能执行过多的异步操作,sarfari 对这块限制尤其死。
我给你的建议,先看看网易云 API 有没有根据根据 id 批量获取播放 url 的接口,按理都应该有的。
如果找不到,那么自己去封装一个接口,这个接口根据 ids 实现批量返回 url,然后接口内部再遍历 id 去调用网易云单个的 API

0 回复 有任何疑惑可以回复我~
  • 提问者 写夜子 #1
    非常感谢!
    回复 有任何疑惑可以回复我~ 2019-03-16 10:00:05
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信