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 · 2 comments
Open

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

rahulinfibrain opened this issue Nov 28, 2024 · 2 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

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

2 participants