我在使用ionic时遇到了使用本地音频 cordova 插件的问题。我已经通过npm安装了native插件。
sudo npm install --save @ionic-native/native-audio
我添加了一个名为smartAudio的新提供商(代码如下)。 它在ionic的Web视图和iOS模拟器/真实设备上都能很好地工作...但由于某种原因,在android模拟器/真实设备上没有声音。
我有一个ion-slides元素,使用*ngFor生成图像幻灯片,就像这样 -
<ion-slides (ionSlideDidChange)="muteAnimalSound()" pager dir="rtl" [loop]="true" >
<ion-slide *ngFor="let slide of animals_slides; let i = index" style="background-color: white">
<img src="{{slide.img_url}}" (click)="playAnimalSound($event)">
</ion-slide>
</ion-slides>
playAnimalSound() 函数看起来像这样 -
playAnimalSound(ev) {
let animalSound = this.getAnimalBySource(ev.target.src);
let currentIndex = this.slides.getActiveIndex();
this.smartAudio.preload(currentIndex, animalSound[0].sound_url);
this.smartAudio.play(currentIndex);
}
我的smartAudio提供商像这样定义 -
export class SmartAudio {
audioType: string = 'html5';
sounds: any = [];
constructor(public nativeAudio: NativeAudio, platform: Platform) {
if(platform.is('cordova')){
this.audioType = 'native';
}
//testing atlassian sourcetree
}
preload(key, asset) {
if(this.audioType === 'html5'){
let audio = {
key: key,
asset: asset,
type: 'html5'
};
this.sounds.push(audio);
} else {
this.nativeAudio.preloadSimple(key, asset);
let audio = {
key: key,
asset: key,
type: 'native'
};
this.sounds.push(audio);
}
}
play(key){
let audio = this.sounds.find((sound) => {
return sound.key === key;
});
if(audio.type === 'html5'){
let audioAsset = new Audio(audio.asset);
audioAsset.play();
} else {
this.nativeAudio.play(audio.asset).then((res) => {
console.log(res);
}, (err) => {
console.log(err);
});
}
}
stop(key)
{
let audio = this.sounds.find((sound) => {
return sound.key === key;
});
if(audio.type === 'html5'){
let audioAsset = new Audio(audio.asset);
audioAsset.play();
} else {
this.nativeAudio.stop(audio.asset).then((res) => {
console.log(res);
}, (err) => {
console.log(err);
});
}
}
}
{ name: 'cat', img_url: './assets/img/animals/cat.jpg', sound_url: './assets/sounds/animals/cat.wav' }
,当用户点击正确的动物时,它的声音应该播放(来自assets/sounds/animals文件夹)。 - Gonras KarolssetTimeout(()=>{ this.smartAudio.play(currentIndex); },3000);
- Swapnil Patwa