A problem with audio_manage Package on my flutter app - android

I try To make a music app and I used the audio_manager package to run a music file the app closed after click play.
I need help with that.
the initial player manager :
final OnAudioQuery _audioQuery = new OnAudioQuery();
and the audio file is an external audio file :
onTap: () {
print("${song.data}");
cubit.audioManager.start("file://${song.uri}", "title", desc: "desc", cover: "assets/image/noaudio.png").catchError((error) {print("error${error}");});
}

If you're using Android then add targetsdk version to 30.

Related

Play Audio in Flutter from URL

I am new to flutter and I want to play audio file from URL path with play, pause and seek button and also show notification in player.
You can play a URL in just_audio like this:
final player = AudioPlayer();
await player.setUrl('https://example.com/song.mp3');
player.play();
player.pause();
player.seek(Duration(seconds: 143);
To add notification support, the easiest way is to add just_audio_background. You need to change the above code slightly so that instead of calling setUrl, you now do this:
await player.setAudioSource(AudioSource.uri(
'https://example.com/song.mp3',
tag: MediaItem(
id: 'Some unique ID',
title: 'Song title',
album: 'Song album',
artUri: Uri.parse('https://example.com/art.jpg'),
),
));
Now once that song starts playing, the supplied metadata will also be shown in the notification.
just_audio_background must also be initialised in your main:
Future<void> main() async {
await JustAudioBackground.init(/* See API for options */);
runApp(MyApp());
}
And don't forget to follow the platform-specific setup instructions for each plugin:
just_audio
just_audio_background
Note that just_audio_background uses the audio_service plugin under the hood, so if your app has more complex requirements, you could use that plugin directly.
If you have questions about how to build the actual UI, you can create a separate question on that, or you can look at the above two links because each plugin includes an example app which demonstrates how to link it all up in a UI.
#2022 Update
After trying the above answers, i was getting this error:
Error: Expected a value of type 'Source', but got one of type 'string'
Here is how i managed to solve it:
Declare a variable of type Source
AudioPlayer myAudioPlayer=AudioPlayer();
late Source audioUrl;
Then initialize it in initstate
audioUrl=UrlSource('https://dummyurl.com/audio1.mp3');
and then you can use it to play audio like this
myAudioPlayer.paly(audioUrl);
Open AndroidManifest.xml file and enable internet permission ,usesCleartextTraffic
android\app\src\main\AndroidManifest.xml
Add following 2 lines for enabling internet permission and usesCleartextTraffic
You can use audioplayers package.
Define AudioPlayer instance like this
AudioPlayer audioPlayer = AudioPlayer();
Play audio as shown below
play() async {
int result = await audioPlayer.play(url);
if (result == 1) {
// success
}
}
You can pause and stop like this
await audioPlayer.pause();
await audioPlayer.stop();
This is how you can play local audio
playLocal() async {
int result = await audioPlayer.play(localPath, isLocal: true);
}
I recommend you to use audio_service package. This is highly customizable with notification and you can also play audio in background or sleep mode.

cordova media plugin isnt working on android 4.4 and 5.0.0

i have tried running cordova media plugin in both kitkat and lollipop but it shows no response.
Not even the 3rd parameter for error's function is running.
I have also read almost every article or question about this problem and tried every way i could but nothing worked.
All i finally concluded was that this plugin is not fully supported in android versions above 4.1
I have tried:
<script>
document.body.onload="ready()";
function ready()
{
document.addEventListener("deviceready",function() {
var src;
// src's value
var med=new Media(src,
function() {
alert("success");
},
function(e)
{
alert("failed code: "+e);
});
med.play();
med.release();},false);
}
</script>
here is what i have tried replacing with //src's value
src = 'cdvfile://audio.mp3';
src = 'file:///android_asset/www/audio.mp3';
src = "cdvfile:///android_asset/www/audio.mp3";
src = "audio.mp3";
even after that stupid conclusion i wrote about up there, i still am doubtful that how it still runs on some devices with same os. So, any ideas of making audio files play in cordova app?
MORE INFO:
1>My project structure
appName
|___www
|___[+]css
|___[+]js
|___index.html
|___[+]img
|___audio.mp3
2>I am targeting 6.3.0 marshmallow 😋
Media definitely works for me on marshmallow - albeit I use wav files rather than mp3. I use
audioFail = loadAudio('sounds/no.wav'); where the file is stored in www/sounds
The media constructor is asynchronous but your code uses med immediately after issuing the call to the constructor - have you confirmed that med exists and is defined before you try to call med.play()?

Streaming mp3 in Xamarin Android MediaManager not working

I'm using this nu-get package to stream mp3 url in a Xamarin Android project:
https://github.com/martijn00/XamarinMediaManager
I followed the instructions in the link up there... and it shows the music playing in the notification bar but it is not working (no sound and it's not even starting the song).
Code snippet:
clickButton.Click += (sender, args) =>
{
ClickButtonEvent();
};
private static async void ClickButtonEvent()
{
await CrossMediaManager.Current.Play("http://www.montemagno.com/sample.mp3");
}
I built the sample included in the link, and I got the same result from their sample. Also deployed on real device too, same result!
Image:
Am I missing something ?
Or is the library broken ?
I ran into this using Android Emulator on Hyper-v. It turns out that the network is set to internal. So the http://www.montemagno.com/sample.mp3 could not be found. My workaround:
Hyper-v -> Virtual Switch Manager, add an external network.
Hyper-v -> Virtual Machines->Settings, add new hardware->Network adapter and set to external network.
"Visual Studio Emulator for Android" desktop app, launch phone vm,
in Visual Studio, deploy and run app.
Sound should work from external source now.
Permissions maybe? In the project site it states that for Android:
You must request AccessWifiState, Internet, MediaContentControl and
WakeLock permissions
By default example use ExoPlayerAudioService.
There are issue with url escape in ExoPlayerAudioService.GetSource method
private IMediaSource GetSource(string url)
{
string escapedUrl = Uri.EscapeDataString(url);
var uri = Android.Net.Uri.Parse(escapedUrl);
var factory = URLUtil.IsHttpUrl(escapedUrl) || URLUtil.IsHttpsUrl(escapedUrl) ? GetHttpFactory() : new FileDataSourceFactory();
var extractorFactory = new DefaultExtractorsFactory();
return new ExtractorMediaSource(uri
, factory
, extractorFactory, null, this);
}
string escapedUrl = Uri.EscapeDataString(url);
I.E. http://example.com/path_to_audio.mp3 will be escaped to "http%3A%2F%2Fexample.com%2Fpath_to_audio.mp3" as result HTTP error.
To fix just skip url escape.

FileReference.load/browse/save wont work when deployed to mobile/android phone

FileReference actions work properly in my workspace but wont when installed in mobile/android phone.
Publish Settings:
Target - Air 3.2 for Android
Script - AS 3.0
Air for Android Settings:
Checked the following
WRITE_EXTERNAL_STORAGE
Here's what's happening, I have 3 buttons calling the FileReference.
One is the for browsing(.browse()) what to load(.load()). Here when I clicked the button for browse, it will prompt "No files selected" even I haven't selected yet. The browse dialog wont even show.
In saving(.save()), it won't show the save dialog box.
Any idea whats happening? all of those are working fine in Flash Pro before publishing
From the AS3 documentation:
Note: In Adobe AIR, the File class, which extends the FileReference class, provides more capabilities and has less security restrictions than the FileReference class.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html
Try something like:
import flash.filesystem.*;
var _file:File = File.applicationStorageDirectory.resolvePath("yourfile.xml");
var _readFileStream:FileStream = new FileStream();
_readFileStream.open(Main._file, FileMode.READ);
var _loadedData:String = String(_readFileStream.readUTFBytes(_readFileStream.bytesAvailable));
_readFileStream.close();
trace(_loadedData);
and to save
var _file:File = File.applicationStorageDirectory.resolvePath("yourfile.xml");
var _writeFileStream:FileStream = new FileStream();
_writeFileStream.open(Main._file, FileMode.WRITE);
_writeFileStream.writeUTFBytes(_loadedData);
_writeFileStream.close();

How to play sounds on Cordova Android web app [duplicate]

This question already has answers here:
Play sound on Phonegap app for Android
(6 answers)
Closed 8 years ago.
I'm creating an android web app and it's simple thing. I have a button and I want it to play a sound when clicked.
I'v searched a lot and actually no proper solution that could help me out.
I'm a newbie on this part and I really have no idea how I can play my sound.
any help will be appreciated.
Edited :
I installed media api on cordova :
var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]);
this is my html part :
<img src="images/applaud.png"></li>
this is the javascript part :
$("#applaud").bind('tap', function() {
var media = new Media("lib/sounds/hooray.mp3", mediaSuccess);
media.play();
});
BTW I'm using jQuery Mobile for this application. Should I do anything else.
Thanks to those who answered my questions.
Update :
I tried this code too ->
function playAudio(id) {
var audioElement = document.getElementById(id);
var url = audioElement.getAttribute('src');
var my_media = new Media(url,
// success callback
function () { alert("success"); },
// error callback
function (err) { alert("error"); }
);
// Play audio
my_media.play();
}
and then in my html it will be like this :
<img src="images/applaud.png">
still nothing, I even revert my cordova to version 3.1 but nothing
guys I really need help.
It sounds like you're developing an HTML web app. Try the HTML5 audio tag.

Categories

Resources