Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Network audio load but can not change wave playing properly #367

Open
rahulinfibrain opened this issue Nov 28, 2024 · 3 comments
Open

Network audio load but can not change wave playing properly #367

rahulinfibrain opened this issue Nov 28, 2024 · 3 comments
Labels
waiting-for-response Waiting for someone to respond.

Comments

@rahulinfibrain
Copy link

This is our code

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:audio_waveforms/audio_waveforms.dart';

class AudioPlayerWidget extends StatefulWidget {
final String audioPath;

const AudioPlayerWidget({
Key? key,
required this.audioPath,
}) : super(key: key);

@OverRide
_AudioPlayerWidgetState createState() => _AudioPlayerWidgetState();
}

class _AudioPlayerWidgetState extends State {
late AudioPlayer _audioPlayer;
late PlayerController _waveformController;
bool _isPlaying = false;
Duration _currentPosition = Duration.zero;
Duration _totalDuration = Duration.zero;
final playerWaveStyle = PlayerWaveStyle(
fixedWaveColor: AppColor.appDeActiveColor,
liveWaveColor: AppColor.appPrimaryColor2,
spacing: 4,
waveCap: StrokeCap.round,
waveThickness: 2.0,
);
@OverRide
void initState() {
super.initState();
_audioPlayer = AudioPlayer();
_waveformController = PlayerController();
_setupAudio();
}

Future _setupAudio() async {
try {
await _audioPlayer.setUrl(widget.audioPath);
_totalDuration = _audioPlayer.duration ?? Duration.zero;
final waveformWidth = MediaQuery.of(context).size.width / 2;
_waveformController.extractWaveformData(
path: widget.audioPath,
noOfSamples: playerWaveStyle.getSamplesForWidth(waveformWidth),
);
_audioPlayer.positionStream.listen((position) {
setState(() {
_currentPosition = position;
if (_currentPosition == _totalDuration) {
_currentPosition = Duration.zero;
_togglePlayPause();
}
});
});

  // Extract waveform data only once

} catch (e) {
  debugPrint("Error setting up audio: $e");
}

}

void _togglePlayPause() {
if (_isPlaying) {
_audioPlayer.pause();
} else {
_audioPlayer.play();
}
setState(() {
_isPlaying = !_isPlaying;
});
}

@OverRide
void dispose() {
_audioPlayer.dispose();
_waveformController.dispose();
super.dispose();
}

@OverRide
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: AppColor.appPrimaryColor.withOpacity(0.10),
borderRadius: BorderRadius.circular(20),
),
child: Row(
children: [
GestureDetector(
onTap: _togglePlayPause,
child: Icon(
_isPlaying ? Icons.pause_circle : Icons.play_circle_filled_sharp,
size: 50,
color: AppColor.appPrimaryColor2,
),
),
const SizedBox(width: 16),

      // Waveform Visualization
      Expanded(
        child: AudioFileWaveforms(
          playerController: _waveformController,
          size: Size(MediaQuery.of(context).size.width, 50),
          waveformType: WaveformType.fitWidth,
          playerWaveStyle: playerWaveStyle,
          continuousWaveform: true,
          animationDuration: Duration(milliseconds: 300),
        ),
      ),
      const SizedBox(width: 16),

      // Time Display
      Text(
        "${_formatDuration(_currentPosition)} / ${_formatDuration(_totalDuration)}",
        style: Fonts.regularTextStyle.copyWith(
          color: AppColor.appPrimaryColor,
          height: fontSize_14 / fontSize_14,
          fontSize: fontSize_14,
          fontWeight: FontWeight.w400,
        ),
      ),
    ],
  ),
);

}

String _formatDuration(Duration duration) {
final minutes = duration.inMinutes.toString().padLeft(2, '0');
final seconds = (duration.inSeconds % 60).toString().padLeft(2, '0');
return "$minutes:$seconds";
}
}

please provider how to update wave

@jay-simformsolutions
Copy link
Collaborator

Hello @rahulinfibrain, We do not provide the functionality to load audio from online URLs.

Can you please explain how you can download the audio from online URLs?

@jay-simformsolutions jay-simformsolutions added the waiting-for-response Waiting for someone to respond. label Nov 28, 2024
@rahulinfibrain
Copy link
Author

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class AudioDownloader {
final Dio _dio = Dio();

/// Request storage permissions
Future _requestPermission() async {
if (await Permission.storage.request().isGranted) {
return true;
}
return false;
}

/// Get the specific folder for saving audio files
Future _getDownloadDirectory() async {
Directory? directory;
if (Platform.isAndroid) {
directory = await getExternalStorageDirectory();
// Create a custom folder for audio files
final path = "/storage/emulated/0/Download/projectName";
directory = Directory(path);
} else {
directory = await getApplicationDocumentsDirectory();
}

if (!directory.existsSync()) {
  await directory.create(recursive: true);
}
return directory;

}

/// Download the audio file
Future<String?> downloadAudio(String url, String fileName) async {
if (!await _requestPermission()) {
print("Permission denied");
return null;
}

final directory = await _getDownloadDirectory();
final filePath = "${directory.path}/$fileName";

try {
  final downloadPath=await getLocalFilePath(fileName);
  if(downloadPath!=null){
    print("Saved file path : $downloadPath");
    return downloadPath;
  }
  else{
    await _dio.download(url, filePath);
    print("Downloaded file saved at: $filePath");
    return filePath;
  }
} catch (e) {
  print("Download failed: $e");
  return null;
}

}
Future<String?> getLocalFilePath(String fileName) async {
try {
// Get the app's storage directory
Directory? directory;
if (Platform.isAndroid) {
directory = await getExternalStorageDirectory();
// Create a custom folder for audio files
final path = "/storage/emulated/0/Download/projectName";
directory = Directory(path);
} else {
directory = await getApplicationDocumentsDirectory();
}

  // Construct the full file path
  final filePath = "${directory.path}/$fileName";

  // Check if the file exists
  final file = File(filePath);
  if (await file.exists()) {
    return filePath;
  } else {
    print("File does not exist: $filePath");
    return null;
  }
} catch (e) {
  print("Error retrieving file path: $e");
  return null;
}

}
}

this is our download audio file code

@manoj-simform
Copy link
Collaborator

@rahulinfibrain I have prepared a sample demo by understanding your requirements, and I am not facing the issue that you have mentioned. Please refer to the below code and do let me know if I miss anything. 

import 'dart:async';
import 'dart:io';

import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';

class NetworkFileDemo extends StatefulWidget {
  const NetworkFileDemo({super.key});

  @override
  State<NetworkFileDemo> createState() => _NetworkFileDemoState();
}

class _NetworkFileDemoState extends State<NetworkFileDemo> {
  final PlayerController playerController = PlayerController();
  late StreamSubscription<PlayerState> playerStateSubscription;

  bool isFilePrepared = false;

  final playerWaveStyle = const PlayerWaveStyle(
    fixedWaveColor: Colors.white54,
    liveWaveColor: Colors.white,
    spacing: 6,
  );
  File? musicFile;

  @override
  void dispose() {
    playerStateSubscription.cancel();
    playerController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Network music file demo'),
      ),
      body: Center(
        child: Column(
          children: [
            TextButton(
              onPressed: () async {
                final res = await http.get(
                  Uri.parse(
                      'https://filesamples.com/samples/audio/mp3/sample4.mp3'),
                );

                final appDirectory = await getApplicationDocumentsDirectory();
                final path = "${appDirectory.path}/recording.mp3";

                musicFile = File(path);

                await musicFile!.writeAsBytes(res.bodyBytes);

                setState(() {});
              },
              child: const Text('Load music file from url'),
            ),
            TextButton(
              onPressed: musicFile == null
                  ? null
                  : () async {
                      if (musicFile != null) {
                        isFilePrepared = true;
                        setState(() {});
                        await playerController.preparePlayer(
                            path: musicFile!.path);
                        playerStateSubscription =
                            playerController.onPlayerStateChanged.listen((_) {
                          setState(() {});
                        });
                      }
                    },
              child: const Text('Prepare music player'),
            ),
            if (isFilePrepared) ...[
              Container(
                padding: const EdgeInsets.only(
                  bottom: 6,
                  right: 10,
                  top: 6,
                ),
                margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                  color: const Color(0xFF343145),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    IconButton(
                      onPressed: () async {
                        playerController.playerState.isPlaying
                            ? await playerController.pausePlayer()
                            : await playerController.startPlayer();
                        playerController.setFinishMode(
                            finishMode: FinishMode.loop);
                      },
                      icon: Icon(
                        playerController.playerState.isPlaying
                            ? Icons.stop
                            : Icons.play_arrow,
                      ),
                      color: Colors.white,
                      splashColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                    ),
                    AudioFileWaveforms(
                      size: Size(MediaQuery.of(context).size.width / 2, 70),
                      playerController: playerController,
                      waveformType: WaveformType.long,
                      playerWaveStyle: playerWaveStyle,
                    ),
                    const SizedBox(width: 10),
                  ],
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
waiting-for-response Waiting for someone to respond.
Projects
None yet
Development

No branches or pull requests

3 participants