Mostrando entradas con la etiqueta angular 2. Mostrar todas las entradas
Mostrando entradas con la etiqueta angular 2. Mostrar todas las entradas

viernes, 9 de marzo de 2018

How to add music to your Website in Javascript

Hi there!

Today I want to talk about "how to add music to your website with the Html Web API".

We are going to use the Html Audio object instead of other proposed solutions on the net, like use Howler.js or other audio frameworks.

For use this solutions, you need to use Javascript or other language compile Javascript, like Angular or Ionic.

Declaration of variables:

loaded: boolean = false;
playing: boolean = false;
sound: any;

First, create the Audio object and define the default properties:

this.sound = new Audio();
this.sound.autoplay = false;
this.sound.preload = 'auto';
this.sound.autobuffer = true;


Before you define the events, you must declare a local variable pointing to this:

let parent = this;

Then, you have to define the audio event listeners:

this.sound.addEventListener('loadeddata', function() {
console.log("music loaded");
parent.loaded = true;
parent.playTrack();
}, false);


this.sound.addEventListener('play', function() {
console.log("music play");
parent.playing = true;
}, false);


this.sound.addEventListener('pause', function() {
console.log("music pause");
parent.playing = false;
}, false);

And for last you need to define the music src and load it:

this.sound.src = './assets/audio/Rhodesia_MkII.mp3';
this.sound.load();

Now, you need the actions and functions called from the html:

isLoadedTrack() {
return this.loaded;
}

isPlayingTrack() {
return this.playing;
}

playTrack() {
if(this.sound) {
this.sound.play();
}
}

pauseTrack() {
if(this.sound) {
this.sound.pause();
}
}

And the content of the html will look like this:

<div *ngIf="isLoadedTrack()">
      <div class="music" *ngIf="!isPlayingTrack()">
          <button (click)="playTrack()">
<i class="fa fa-play"></i> <i class="fa fa-music"></i>
</button>
      </div>
      <div class="music" *ngIf="isPlayingTrack()">
          <button (click)="pauseTrack()">
<i class="fa fa-pause"></i> <i class="fa fa-music"></i>
</button>
      </div>
</div>

And the result will show those two state:



I hope you find the talk interesting!

You can see the Production use of the Component on https://davidmartinezros.com
And you can take a look to the Portfolio repository: https://github.com/davidmartinezros/portfolio

Any doubt, ask me and I will answer as soon as possible.

viernes, 23 de febrero de 2018

Internationalization in Angular

Here we come again!

Today we will learn how to implement the internationalization in angular easily and in a few steps.

Step 1: Add the necessary libraries to our package.json file.

"dependencies": {
...
"@ngx-translate/core": "8.0.0",
"@ngx-translate/http-loader": "2.0.0",
...
},

Step 2: Configure our application to use a folder of language files.

app.module.ts


import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';


@NgModule({
declarations: [ AppComponent ],
imports: [
...
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
}
})
...
],
providers: [ ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

Step 3: Define a component where you can change the language.

language;

languages: Language[] = [
new Language("ca","CATALÀ"),
new Language("es","ESPAÑOL"),
new Language("en","ENGLISH")
];

constructor(private route: ActivatedRoute,
private translate: TranslateService) {
var userLang = "";
this.route.queryParams.subscribe(params => {
if(!params['lang'] || params['lang'] == "") {
userLang = this.language;
} else {
userLang = params['lang'];
}
console.log("queryParams:" + userLang);

if(!userLang || userLang == "") {
userLang = navigator.language;
}

if(userLang) {
userLang = userLang.toLowerCase();
if(userLang.length > 2) {
userLang = userLang.substring(0, 2);
}
}
if(userLang == "ca" || userLang == "es" || userLang == "en") {
this.changeLanguage(userLang);
} else {
this.changeLanguage("ca");
}
});
}

public changeLanguage(language) {

console.log(language);

// canviar l'idioma per defecte usat a les traduccions
this.translate.setDefaultLang(language);
// canviar l'idioma a usar per fer les traduccions
this.translate.use(language);

// canviem l'idioma seleccionat
this.language = language;
}

@NgModule({
imports: [ ... ],
declarations: [ ... ],
exports: [ ...],
providers: [ TranslateService ]
})

Step 4: Use the Pipe translate to get the translations of the language files.

pageComponent.html

...
{{ 'field' | translate }}
...

Step 5: Create the json files with the translations.

en.json


{
"field": "traduction of my first field"
}

Here we could make all the necessary translations in our pages and components.

If we wanted that when choosing a language, the other components and pages of our application were translated, where we had loaded arrays of information, we should do the following:

Step 1: Subscribe an Observable where to load the array.

projects: Project[];

public static updateStuff: Subject<any> = new Subject();

constructor(
private projectService: ProjectService) {
ProjectsComponent.updateStuff.subscribe(res => {
// here fire functions that fetch the data from the api
this.getProjects();
});
}

ngOnInit(): void {
this.getProjects();
}

getProjects(): void {
this.projectService.getProjects()
.then(projects =>
{ this.projects = projects }
);
}

Step 2: Call the Subscription when we change the language.

import { ProjectsComponent } from '../projects/projects.component';

public changeLanguage(language) {
...
ProjectsComponent.updateStuff.next(false);
...
}

I hope you have helped the tutorial.

Any questions, do not hesitate to ask.