2017-10-21 43 views
2

我有一个简单的角度应用程序中使用下面的JavaScript网页音频对象是角视图模型后没有更新的变化

app.component.ts

export class AppComponent { 
    title = 'media player'; 
    audio; 
    currentTime: number; 

    constructor() { 
    this.audio = new Audio(); 
    this.audio.src = './Music/demo2.MP3'; 
    this.audio.play(); 
    this.currentTime = this.audio.currentTime; 
    } 
} 

和 app.component.ts

播放音频
<h4>{{ currentTime }}</h4> 

一切工作正常,但认为不作为模型更新改变

+1

您不能绑定到'audio.currentTime'吗? – user184994

+0

这是因为此行'this.currentTime = this.audio.currentTime;'只在组件加载时运行一次。您需要确保每秒更新一行。或者@ user184994方法也可以工作。 –

+0

@PraveenM是我低于和'this.currentTime = this.audio.currentTime;'只运行一次。请你知道一种方法来使这些工作。 –

回答

1

角不更新浏览器的事件相同的角用途zonejs这猴子补丁几个浏览器事件绑定,它触发detectChanges方法保持同步结合。

在这种情况下,Angular不会更新绑定,因为Audio API事件不会通过zonejs进行修补。对于这种情况,您必须手动运行更改检测以手动更新绑定。您可以使用audio API的ontimeupdate事件处理程序。

import { ChangeDetectorRef, Component } from '@angular/core'; 

export class AppComponent { 
    title = 'media player'; 
    audio; 
    currentTime: number; 

    constructor(private cd: ChangeDetectorRef) { 
    } 
    ngOnInit(){ 
    this.audio = new Audio(); 
    this.audio.src = './Music/demo2.MP3'; 
    this.audio.play(); 
    //this will make sure to update when time updates. 
    this.audio.ontimeupdate = (event) => { 
     this.currentTime = this.audio.currentTime; 
     this.cd.detectChanges(); 
    } 
    } 
} 
+0

作品像魅力..非常感谢! –

-2

这里是setInterval方法

export class AppComponent { 
 
    title: string = 'media player'; 
 
    audio: Audio; 
 
    currentTime: number; 
 

 
    constructor() { 
 
    this.audio = new Audio(); 
 
    this.audio.src = './Music/demo2.MP3'; 
 
    this.audio.play(); 
 
    this.currentTime = this.audio.currentTime; 
 
    } 
 
    
 
    ngOnInit() { 
 
    setInterval(() => { 
 
     this.currentTime = this.audio.currentTime; 
 
    }, 1000); 
 
    } 
 
}

但是如前所述,单纯只使用audio.currentTime的前端可能会简单得多,有效的方法的@ user184994

<h4>{{ audio.currentTime }}</h4>

+0

我认为'setInterval'代码味道。它使代码和测试复杂化,并且在OP正试图完成时似乎没有必要。 – stealththeninja

+0

@stealththeninja OP的问题是'currentTime'在音频播放时不会持续更新,这是我会考虑的一种方法。这就是为什么我提到使用'audio.currentTime'本身,正如我所假设的那样,在音频播放过程中会更新,这是非常稳定和有效的。 –

+0

最好是通过'setInterval'使用事件侦听器,媒体元素有'timeupdate'事件:https://developer.mozilla.org/en-US/docs/Web/Events/timeupdate – stealththeninja