Skip to content

Could not request audio focus Error: Could not request audio focus onAndroid 14 version : 6.4.4 #2

@pap5508

Description

@pap5508

audio file plays once but try to play second time throws following error on Android.
iOS works fine

{
  "description": "NativeScript Application",
  "version": "1.1.21",
  "license": "MIT",
  "name": "TestApp",
  "readme": "NativeScript Application",
  "repository": "<fill-your-repository-here>",
  "dependencies": {
    "@angular/animations": "~15.1.0",
    "@angular/common": "~15.1.0",
    "@angular/compiler": "~15.1.0",
    "@angular/core": "~15.1.0",
    "@angular/forms": "~15.1.0",
    "@angular/platform-browser": "~15.1.0",
    "@angular/platform-browser-dynamic": "~15.1.0",
    "@angular/router": "~15.1.0",
    "@finalsite/rich-text-editor": "^0.1.1",
    "@nativescript-community/audio": "^6.4.4",
    "@nativescript-community/ui-barcodeview": "^3.6.1",
    "@nativescript-community/ui-document-picker": "^1.1.12",
    "@nativescript-community/ui-material-bottomnavigationbar": "^7.2.44",
    "@nativescript-community/ui-pulltorefresh": "^2.5.3",
    "@nativescript-use/nativescript-orientation": "^0.0.3",
    "@nativescript/angular": "^15.0.1",
    "@nativescript/appversion": "^2.0.0",
    "@nativescript/background-http": "^6.0.1",
    "@nativescript/biometrics": "^1.3.1",
    "@nativescript/camera": "~5.0.15",
    "@nativescript/core": "~8.2.5",
    "@nativescript/datetimepicker": "^2.1.13",
    "@nativescript/firebase": "11.1.3",
    "@nativescript/firebase-core": "^3.2.0",
    "@nativescript/firebase-messaging": "^3.2.0",
    "@nativescript/imagepicker": "^3.0.0",
    "@nativescript/iqkeyboardmanager": "^2.1.1",
    "@nativescript/local-notifications": "^6.1.1",
    "@nativescript/secure-storage": "^3.0.3",
    "@nativescript/theme": "^2.5.0",
    "@ngx-translate/core": "^14.0.0",
    "@ngx-translate/http-loader": "^7.0.0",
    "@nota/nativescript-webview-ext": "^8.0.2",
    "@nstudio/nativescript-cardview": "^2.0.2",
    "@nstudio/nativescript-carousel": "^8.0.3",
    "@nstudio/nativescript-checkbox": "^2.0.5",
    "@nstudio/nativescript-floatingactionbutton": "^3.0.4",
    "@nstudio/nativescript-pulltorefresh": "^3.0.2",
    "@nstudio/nativescript-snackbar": "^2.1.0",
    "@triniwiz/nativescript-image-cache-it": "7.4.0",
    "autolinker": "^4.0.0",
    "bootstrap": "^4.5.2",
    "email-validator": "^2.0.4",
    "enhanced-resolve": "^4.1.1",
    "jwt-decode": "^2.2.0",
    "moment": "^2.30.1",
    "nativescript": "^8.6.5",
    "nativescript-audio": "~6.2.6",
    "nativescript-drop-down": "~6.0.2",
    "nativescript-imagecropper": "~4.0.3",
    "nativescript-livesync": "^1.4.1",
    "nativescript-mediafilepicker": "~4.0.2",
    "nativescript-modal-datetimepicker": "~2.1.5",
    "nativescript-oauth2": "~3.0.10",
    "nativescript-permissions": "~1.3.12",
    "nativescript-phone": "^3.0.3",
    "nativescript-screen-orientation": "~2.0.0",
    "nativescript-sqlite": "~2.8.6",
    "nativescript-themes": "^2.0.2",
    "nativescript-ui-listview": "~15.2.3",
    "nativescript-webview-utils": "~4.0.0",
    "ngx-linky": "~4.0.0",
    "qs": "npm:querystring@^0.2.1",
    "rxjs": "~7.5.0",
    "util": "^0.12.5",
    "zone.js": "^0.11.6"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~15.1.0",
    "@angular/compiler-cli": "~15.1.0",
    "@babel/runtime": "7.20.7",
    "@nativescript/android": "8.6.2",
    "@nativescript/ios": "8.6.3",
    "@nativescript/types": "~8.4.0",
    "@nativescript/webpack": "~5.0.18",
    "@ngtools/webpack": "~15.1.0",
    "sass": "^1.34.1",
    "typescript": "~4.9.4"
  },
  "scripts": {
    "ns-bundle": "ns-bundle"
  },
  "main": "app/main.ts",
  "hooks": []
}

    public async playRecord(
        attachment = undefined,
        attachmentId = undefined,
        args,
        repeat: boolean = false
    ) {


        console.log("attachment.filepath: " + attachment.filepath);
        let recordedFile: File = null;

        console.log("1...........................  "+ attachment.filepath);

        //Pause current playing file if another file is tapped and reset variables
        if (attachmentId !== this.currentPlayingAttachmentId && attachmentId !== this.currentPausedAttachmentId) {
            console.log("2...........................  "+ attachment.filepath);

            try {
                if (this._player.isAudioPlaying()) {
                    console.log("3...........................  "+ attachment.filepath);

                    await this.pauseRecord(this.currentPlayingAttachmentId);
                }
            } catch (error) {
                console.log("there was an error pausing the record");
            }

            //reset for new file
            this.isPlaying = false;
            this.isPaused = false;
            this.tapped = false;
            timer.clearInterval(this.timerId);
            this.progressInMilliseconds = 0;
            this.progressInSeconds = 0;
            this.currentPlaytimeInMilliseconds = 0;
            this.currentPlaytimeInSeconds = 0;
            this.currentPausedAttachmentId = null;
            this.currentPlayingAttachmentId = null;
            this.remainingDuration = 0;
            this.changeDetectionRef.detectChanges();
            this._player.dispose().then(() => console.log("player disposed"));
        }

        if (attachment.filepath && File.exists(attachment.filepath)) {
            console.log("4...........................  "+ attachment.filepath);
            recordedFile = File.fromPath(attachment.filepath);
        }
        if (
            !recordedFile ||
            !attachment.filepath ||
            !File.exists(attachment.filepath)
        ) {
            try {
                console.log("file not foumnd, try download");

                var downloadparent = args.object.parent;
                var downloadActivityIndicator = this.downloadActivityIndicator
                    ? this.downloadActivityIndicator.nativeElement
                    : downloadparent.getViewById("DownloadActivityIndicator");

                if (downloadActivityIndicator) {
                    downloadActivityIndicator.busy = true;
                    downloadActivityIndicator.visibility = "visible";
                }
                this.changeDetectionRef.detectChanges();
                await this.checkPermissions().then((granted) => {
                    if (granted) {
                        if (isAndroid) {
                            return this.attachmentsService
                                .downloadAttachment(attachment, this.chat.name)
                                .then((fileExist) => {
                                    if (fileExist === "false" || fileExist == null) {
                                        return Promise.reject("file not found");
                                    } else {
                                        recordedFile = File.fromPath(attachment.filepath);
                                        if (downloadActivityIndicator) {
                                            downloadActivityIndicator.busy = false;
                                            downloadActivityIndicator.visibility = "collapsed";
                                        }
                                        this.changeDetectionRef.detectChanges();
                                        return Promise.resolve();
                                    }
                                });
                        } else {
                            return this.attachmentsService
                                .iosAttachment(attachment, this.chat.name)
                                .then((fileExist) => {
                                    if (fileExist == "false" || fileExist == null) {
                                        return Promise.reject("file not found");
                                    } else {
                                        recordedFile = File.fromPath(attachment.filepath);
                                        if (downloadActivityIndicator) {
                                            downloadActivityIndicator.busy = false;
                                            downloadActivityIndicator.visibility = "collapsed";
                                        }
                                        this.changeDetectionRef.detectChanges();
                                        return Promise.resolve();
                                    }
                                });
                        }
                    }
                });

                if (!File.exists(recordedFile.path)) {
                    console.log("download failed");
                    return;
                }
            } catch {
                console.log("could not dl file");
                return;
            }
        }

        if (recordedFile === null) {
            console.log("no audio file found");
            return;
        }


        if (this.isPaused && !repeat) {
            console.log("5...........................  "+ attachment.filepath);
            this.isPaused = false;
            this.isPlaying = true;
            this.currentPausedAttachmentId = null;
            this.currentPlayingAttachmentId = attachmentId;
            this.changeDetectionRef.detectChanges();
            this.tapped = false;
            this._player.resume();

            if (!this._player.isAudioPlaying()) {
                this.isPaused = false;
                this.isPlaying = false;
                this.currentPlaytimeInMilliseconds = 0;
                this.currentPlaytimeInSeconds = 0;
                timer.clearInterval(this.timerId);
                this.changeDetectionRef.detectChanges();
                return;
            }
            return;
        }

        console.log("RECORDED FILE : " + JSON.stringify(recordedFile));
        const playerOptions: AudioPlayerOptions = {
            audioFile: recordedFile.path,
            loop: false,
            completeCallback: () => {
                console.log("6...........................  "+ attachment.filepath);
                console.log("Audio file complete.");
                this.isPlaying = false;
                this.isPaused = false;
                this.tapped = false;
                timer.clearInterval(this.timerId);
                this.progressInMilliseconds = 0;
                this.progressInSeconds = 0;
                this.changeDetectionRef.detectChanges();
                this.currentPausedAttachmentId = null;
                this.currentPlayingAttachmentId = null;
                this.remainingDuration = 0;
                this.changeDetectionRef.detectChanges();
                if (!playerOptions.loop) {
                    this._player.dispose().then(() => console.log("player disposed"));
                }
            },

            errorCallback: (errorObject) => {
                console.log("7...........................  "+ attachment.filepath);
                console.log(JSON.stringify(errorObject));
                this.isPlaying = false;
                this.tapped = false;
                this.isPaused = false;
                this.currentPausedAttachmentId = null;
                this.currentPlayingAttachmentId = null;
                this.remainingDuration = 0;
                this.progressInMilliseconds = 0;
                this.progressInSeconds = 0;
                if (!this.isDisposed) {
                    this.changeDetectionRef.detectChanges();
                }
            },

            infoCallback: (infoObject) => {
                console.log("8...........................  "+ attachment.filepath);
                console.log(JSON.stringify(infoObject));
            },
        };



        this._player.playFromFile(playerOptions).then(
            (played) => {
                console.log("9...........................  "+ JSON.stringify(playerOptions));
                console.log("file played", played);
                this.isPlaying = true;
                this.isPaused = false;
                this.currentPausedAttachmentId = null;
                this.currentPlayingAttachmentId = attachmentId;
                this.changeDetectionRef.detectChanges();
                this._player.getAudioTrackDuration().then((duration) => {
                    this.audioTrackDurationInSeconds = platform.isAndroid
                        ? this.roundMillisecondsToNearestSecond(+duration)
                        : +duration;
                    this.audioTrackDurationInMilliseconds = platform.isAndroid
                        ? +duration
                        : +duration * 1000;
                    // start audio duration tracking
                    this.startDurationTracking(
                        this.audioTrackDurationInSeconds,
                        this.audioTrackDurationInMilliseconds
                    );
                });
            },
            (err) => {
                console.log("error playFromFile");
                this.isPlaying = false;
                this.isPaused = false;
                this.currentPausedAttachmentId = null;
                this.currentPlayingAttachmentId = null;
            }
        );
    }




Unhandled Promise rejection: Could not request audio focus ; Zone: <root> ; Task: null ; Value: Error: Could not request audio focus Error: Could not request audio focus
      at file: app/webpack:/TestApp/node_modules/@nativescript-community/audio/android/player.js:278:22
      at Generator.next (<anonymous>)
      at asyncGeneratorStep (file: app/webpack:/TestApp/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:3:0)
      at _next (file: app/webpack:/TestApp/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:22:0)
      at file: app/webpack:/TestApp/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:27:0
      at new ZoneAwarePromise (file: app/webpack:/TestApp/node_modules/zone.js/fesm2015/zone.js:1429:0)
      at file: app/webpack:/TestApp/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:19:0
      at TNSPlayer.play (file: app/webpack:/TestApp/node_modules/@nativescript-community/audio/android/player.js:295:9)
      at android.media.MediaPlayer.OnPreparedListener.onPrepared (file: app/webpack:/TestApp/node_modules/@nativescript-community/audio/android/player.js:221:37)
  onScroll:18 test: 1804

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions