nstudio / nativescript-audio

:microphone: NativeScript plugin to record and play audio :musical_note:
Other
150 stars 104 forks source link

How to play multiple audios? (dispose method seems not close file) #120

Open fielding34 opened 6 years ago

fielding34 commented 6 years ago

I am using below code to try playing multiple audios. When playAudio() is invoked for the fourth audio file, initFromFile() will fail with exception pasted as below. It seems too many files are open so iOS refuse to open more. I have already invoked the dispose(), but it doesn't work.

I wonder if there is another way to play multiple audios or dispose() should close file.

const audio = require('nativescript-audio');

let player = new audio.TNSPlayer();

const playOptions = {
    audioFile: '',
    loop: false,
    completeCallback: function () {
        console.log('finished playing');
    },
    errorCallback: function (err) {
        console.log('option error: ', JSON.stringify(err));
    },
    infoCallback: function (args) {
        console.log('option info', JSON.stringify(args));
    }
}

exports.playAudio = function (file) {
    console.log('play audio ' + file);
    if (file != playOptions.audioFile) {
        playOptions.audioFile = file;
        console.log('---------1');
        player.dispose().then(() => {
            console.log('---------2');
            player.initFromFile(playOptions).then(() => {
                console.log('###', player._player);
                player.play();
            }).catch(err => {
                console.log('$$$', err);
            });;

        }).catch(err=> {
            console.log('dispose error', err);
        });;
    } else {
        if (player.isAudioPlaying()) {
            player.pause().then(() => {
                player.play();
            });
        } else {
            player.play();
        }
  }
CONSOLE LOG file:///app/util/audio.js:30:16: play audio ~/resources/mp3_word/004_ball.mp3
CONSOLE LOG file:///app/util/audio.js:33:20: ---------1
CONSOLE LOG file:///app/util/audio.js:35:24: ---------2
CONSOLE LOG file:///app/util/audio.js:40:28: $$$ Error Domain=NSOSStatusErrorDomain Code=-42 "(null)"
bradmartin commented 6 years ago

dispose ends up resetting the iOS player when called. Ideally, you only dispose it when you are done playing audio files and want to destroy the instance. If you call dispose you should recreate a new instance of the TNSPlayer, which creates a new native audio player as well.