stream a live audio stream for android - java

I am new to android programming and therefore this might seem like an easy question for many but its been 2 days and i have searched almost everywhere on the internet but cant find a solution to my problem
i am trying to stream a link(which works when i post on chrome) using MediaPlayer class. Although i get audio on chrome, i never get anything when i run the app on my Samsung galaxy s4.i have already used internet permission for the app. here is the code i am using:
public class LiveKirtan extends Activity {
MediaPlayer mp;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_kirtan);
url = "http://radio2.sikhnet.com:8020/live";
Uri myUri = Uri.parse(url);
mp = new MediaPlayer();
try {
mp.setDataSource(this, myUri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.start();
}
});
}
}

Make sure to add the following permission to your manifest:
<uses-permission android:name="android.permission.INTERNET"/>
Also, Android does not support just any kind of streaming audio (especially pre kitkat), so make sure to check the compatibility of your stream here.

Related

Android Mediaplayer Null point Exception (Java)

I am trying to create Mediaplayer session with given uri. but it causes NullpointerException.
Uri uri = Uri.parse(path);
// Creating MediaPlayer with given song's URI
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
mediaPlayer = MediaPlayer.create(this, uri);
try {
// Setting the MediaPlayer Listener
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
mediaPlayer.start();
changeSeekbar();
}
});
} catch (Exception e) {
Log.e("ERROR", e.toString());
}
Given Logcat:
2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/Path: /storage/emulated/0/Music/Alone - Viren.mp3
2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/ERROR: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setOnPreparedListener(android.media.MediaPlayer$OnPreparedListener)' on a null object reference
Could you Tell me What i am doing wrong ? Thanks.
There are two ways to write this code, both tested on the device
First of all, make sure you handle android.permission.READ_EXTERNAL_STORAGE correctly and you really have correct Uri.
MediaPlayer.create(this, uri); will fail if either context or uri are invalid.
MediaPlayer.create(this, uri); which itself already prepares player so you don't need .prepareAsync() in this situation. and your code is good to go.
another way:
mediaPlayer = new MediaPlayer(); // hence, we don't use .create, manually instantiate
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(this, uri);
mediaPlayer.setOnPreparedListener(mp -> {
mediaPlayer.start();
});
/* use async, if you don't want to block UI thread
keep in mind, this should be called after setting listener
because it might prepare even until the listener has been set */
mediaPlayer.prepareAsync();
} catch (Exception e) {
Log.e("ERROR", e.toString());
}
Try this :
Uri uri = Uri.parse(path);
mediaPlayer = new MediaPlayer();
try {
// mediaPlayer.setDataSource(String.valueOf(uri));
mediaPlayer.setDataSource(MainActivity.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();

Trouble sending data from Android to Arduino via Bluetooth

I'm trying to set up a system where an android app connects to Arduino via Bluetooth and tells it to either turn on or off its LED. I've looked through a lot of pages and source code and saw many people did it as I did but somehow my code isn't working and I cannot determine why.
Here's the entirety of my Arduino code, really simple and short.
#include <SoftwareSerial.h>
SoftwareSerial Blue(0,1); // rx tx
int LED = 13; // Led connected
char data;
char state = 0;
void setup()
{
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
Serial.begin(9600);
Blue.begin(9600);
}
void loop()
{
while(Blue.available()==0);
if(Blue.available()>0){ // read from android via bluetooth
data = Blue.read();
Serial.println(data);
}
if (data == '1') // If data is 1, turn ON the LED
{
digitalWrite(LED,HIGH);
Serial.println("LED ON ");
}
if( data == '2') // if data is 2, turn OFF the LED
{
digitalWrite(LED,LOW);
Serial.println("LED OFF");
}
}
And here's a snippet of my android code that sends data to Arduino to control LED
switchLight.setOnClickListener(new View.OnClickListener() { // button that will switch LED on and off
#Override
public void onClick(View v) {
Log.i("[BLUETOOTH]", "Attempting to send data");
if (mmSocket.isConnected() && btt != null) { //if we have connection to the bluetoothmodule
if (!lightflag) {
try{
mmSocket.getOutputStream().write("1".toString().getBytes());
showToast("on");
}catch (IOException e) {
showToast("Error");
// TODO Auto-generated catch block
e.printStackTrace();
}
//btt.write(sendtxt.getBytes());
lightflag = true;
} else {
try{
mmSocket.getOutputStream().write("2".toString().getBytes());
showToast("off");
}catch (IOException e) {
showToast("Error");
// TODO Auto-generated catch block
e.printStackTrace();
}
//btt.write(sendtxt.getBytes());
lightflag = false;
}
}
else {
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
});
This is the part of the code that connects to Arduino Bluetooth module. Again, fairly simple stuff and its only purpose are to connect to the module.
BluetoothAdapter bta; //bluetooth stuff
BluetoothSocket mmSocket; //bluetooth stuff
BluetoothDevice mmDevice; //bluetooth stuff
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("[BLUETOOTH]", "Creating listeners");
final TextView response = findViewById(R.id.response);
Button switchLight = findViewById(R.id.switchlight);
Button connectBT = findViewById(R.id.connectBT);
connectBT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BluetoothSocket tmp = null;
mmDevice = bta.getRemoteDevice(MODULE_MAC);
Log.i("[BLUETOOTH]", "Attempting to send data");
try {
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
mmSocket = tmp;
mmSocket.connect();
Log.i("[BLUETOOTH]","Connected to: "+mmDevice.getName());
showToast("Connected to: " + mmDevice.getName());
}catch(IOException e){
try {mmSocket.close();
}catch(IOException c){return;}
}
}
});
When I connect my android to the Arduino and track the serial monitor on Arduino IDE, instead of reading either 1 or 2, it reads something that looks like this:
This is produced using the Serial. println function in my Arduino code and I'm pretty sure it should display 1 or 2 but as you can see it does not. I've tried multiple workarounds like declaring it as int or char etc. If you can pinpoint any issue I'd much appreciate it.

Can't use STREAM_VOICE_CALL to play audio via MediaPlayer in android java

I have tried to play many audio (mp3) files through MediaPlayer's setAudioStreamType(AudioManager.STREAM_VOICE_CALL); but mp.start(); does not play nor does it throw an exception.
The setup works with SoundPool but it is limited to like 5 seconds, some files playing upto 8 seconds.
I am attaching the part of code here:
String s = absolutepath.get(position);
Uri u = Uri.parse(s);
playing = (MediaPlayer) MediaPlayer.create(MainActivity.this, u);
playing.setOnPreparedListener(this);
onPrepared includes this:
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
spProgress.cancel();
mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
try {
mp.start();
} catch (IllegalStateException e) {
Toast.makeText(this, "exception", Toast.LENGTH_SHORT).show();
}
}
I have tried this without the try/catch and even without listener. The only time it plays is when I don't use the stream type STREAM_VOICE_CALL.
The same files can be played with SoundPool:
SoundPool sp = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
sp.load(s, 1);
sp.setOnLoadCompleteListener(this);
Listener:
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
// TODO Auto-generated method stub
if (status == 0) {
spProgress.cancel();
sp.play(sampleId, 1, 1, 1, 0, 1);
} else {
Toast.makeText(this, "failed to load", Toast.LENGTH_SHORT).show();
}
}
I actually had the same problem, and Google's Guide is very bad here - it's indeed a bit tricky, but simple to explain:
As you need to change the STREAM, and then prepare() your MediaPlayer again, you'll get it working by doing this:
Resources res = getResources();
AssetFileDescriptor afd = res.openRawResourceFd(R.raw.tts_a);
mp = new MediaPlayer();
//mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mp.setLooping(false);
try {
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
The actual trick is to NOT use the MediaPlayer.create, as it's calling the prepare itself! Therefore you're not able to set the Stream. By setting the File with AssetFileDescriptor, you can set the Stream and call your prepare() afterwards!

android media player wont play audio file

im making a music app just for fun. I can read all my music files from sd card but MediaPlayer wont play the sound. I have the path to the file which i pass to the media player with setDataSource but nothing happens and i get no exceptions. Here is the code im using.
Uri songUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
setUpViews();
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(songUri.toString());
mp.prepare();
} catch (IllegalArgumentException e) {
Toast.makeText(this, "ILLEGAL ARGUMENT EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (SecurityException e) {
Toast.makeText(this, "SECURITY EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IllegalStateException e) {
Toast.makeText(this, "ILLEGAL STATE EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(this, "IO EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
mp.start();
Log.d("URI AFTER SET UP", songUri.toString());
}
As i said before nothing happens when i open this activity but i still get all the Log.d in the console. Is there any more configurations for the media player to play the music? Thanks in advance.
setDataSource() requires a path argument . You are passing the entire uri as string. Try this :
mp.setDataSource(songUri.getPath());
mp.prepare();
mp.start();
Moreover, if you are trying to access a file with content:// uri, it won't work. You'll have to find the real path to the file, i.e file:// uri.
I think you have to add setAudioStreamType to your MediaPlayer Object. You can add this before mp.setDataSource(your_URI); like below
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
There other types, you can choose AudioManager.STREAM_MUSIC for Music Player
I just solved the problem, and i just dont know why it works. What i did was to put a button to stop the music being played. I dont understand why it works so if someone could explain why it does i'd be thanksfull.
get the path of song by querying MEDIASTORE-EXTERNAL_URI.And this field MEDIASTORE.AUDIO.MEDIA.DATA will give u the path of the song(which is string). U can set it directly to mediaplayer.setDataSource(Your_path_from_mediastore) .It will work fine than.

Pair device in bluetooth android

I am trying to connect another android device by Bluetooth, So first I paired the devices and then I tried sending the request for another device.
When I called the system bluetooth settings screen, I am able to pair the another device
Intent btSettingsIntent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivityForResult(btSettingsIntent, Pair_Request);
When I tried to pair by programmaticaly, I'm getting this dialogue and entered pair digit in my device but no response in another device
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddress);
Intent intent = new Intent("android.bluetooth.device.action.PAIRING_REQUEST");
intent.putExtra("android.bluetooth.device.extra.DEVICE", device);
intent.putExtra("android.bluetooth.device.extra.PAIRING_VARIANT", 0);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
I got this image in device, when I type pair number, I'm not getting anything in another deivce
if the device is already paired , then you can use
if(device.getBondState()==device.BOND_BONDED){
Log.d(TAG,device.getName());
//BluetoothSocket mSocket=null;
try {
mSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
// TODO Auto-generated catch block
Log.d(TAG,"socket not created");
e1.printStackTrace();
}
try{
mSocket.connect();
}
catch(IOException e){
try {
mSocket.close();
Log.d(TAG,"Cannot connect");
} catch (IOException e1) {
Log.d(TAG,"Socket not closed");
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
for the MY_UUID use
private static final UUID MY_UUID = UUID.fromString("0000110E-0000-1000-8000-00805F9B34FB");
the above code snippet is just to connect your device to an A2DP supported device.
I hope it will work. tell me if not.

Categories