I have code to play an .ogg audio file, that I downloaded from the internet. I have no errors, so I can run it, but then the app crashes:
package play.my.sound;
import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
public class PlaySound2Activity extends Activity {
private SoundPool soundPool;
private int soundID;
boolean loaded = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View view = findViewById(R.id.textView1);
view.setOnClickListener((OnClickListener) this);
// Set the hardware buttons to control the music
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the sound
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
soundID = soundPool.load("sound1.ogg", 1);
}
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// Getting the user sound settings
AudioManager audioManager = (AudioManager) getSystemService (AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
Log.e("Test", "Played sound");
}
}
return false;
}
}
I think I have two problems:
I put this in the main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="Click on the screen to start playing"
android:id="#+id/textView1" android:layout_width="fill_parent"
android:layout_height="fill_parent"></TextView>
</LinearLayout>
And I don't know if it's correct.
I put the file sound1.ogg in the workspace->SoundPlay2 folder because in the res folder I had problems, and also, I tried to put it in the two res folders that exist.
This is from my console:
[2012-01-04 19:38:16 - PlaySound2] Failed to install PlaySound2.apk on device 'emulator-5554': timeout
[2012-01-04 19:38:16 - PlaySound2] Launch canceled!
[2012-01-04 19:47:33 - PlaySound2] Error in an XML file: aborting build.
[2012-01-04 19:52:34 - PlaySound2] res\layout\main.xml:0: error: Resource entry main is already defined.
[2012-01-04 19:52:34 - PlaySound2] res\layout\main.out.xml:0: Originally defined here.
[2012-01-04 19:52:34 - PlaySound2] C:\Users\Natalia\workspace\PlaySound2\res\layout\main.out.xml:1: error: Error parsing XML: no element found
I took this example from "Android Sounds - Tutorial".
I want to play an audio file, more specifically, a .wav file.
I dont' know where I can find some information about the files that are permitted in the MediaPlayer class and their characteristic (durantion, sample rate...) Could you tell me where I can find this??
Create raw folder in the res folder and add your file to it. Then play the file using
soundID = soundPool.load(R.raw.sound1, 1);
And also see this post for your main.xml problem.
I've never seen the Class SoundPool before, however I would recommend using a MediaPlayer Class:
mMediaPlayer = new MediaPlayer(this, R.raw.yourfile);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
mMediaPlayer.start();
Make sure you put the file into the folder PROJECT/res/raw/ (or create it if it does not exist)
Also there is something wrong with your main.xml. Can you please post it?
Example for playing some kind of buzzer. In the res folder under raw folder I have a buzzer.wav
Method to play this buzzer:
/**
* Method to play an alarm sound to signal half time or full time.
*/
private void playAlarm() {
MediaPlayer mp = MediaPlayer.create(this,
R.raw.buzzer);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
first you need to save sound1.ogg file in src\main\res\raw directory
instated of direct passing "sound1.ogg" file , pass file this way R.raw.sound1
soundID = soundPool.load(R.raw.sound1, 1);
To be honest I would always prefer Mediaplayer over any other api.After downloading file save it to external storage or raw folder and play it using the given methods or you can directly play it from internet.Caution: Be careful of buffering.
To play audio directly from internet add these code. Note: Api version >= 21 and make sure to add internet permission in manifest
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)//This method requires android version more than 20
public void playSoundFrom_internet(String url) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
try {
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();
}catch(IOException E){
E.printStackTrace();
}
}
To play audio from res folder:
public void playSoundFrom_raw(#RawRes int rawId, Context context){
MediaPlayer mediaPlayer = MediaPlayer.create(context,rawId);
mediaPlayer.start();
}
To play audio from file. Note: Make sure to add storage permission
public void playSoundFrom_file(String filePath){
try {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
That's not how OnClickListener be implemented, that's an Interface to implement in the class not force casted to. You did that as a quick fix but blew back onto you since AudioManager got running first so you thought that is at fault.
Related
I am a completely begginer guy in Android Studio and mobile apps in general. I used to create websites on Wordpress and i don't have so much experience on coding. Recently i started experimenting with mobile apps and mostly Android Studio. I bought a template for a Logo Quiz game and i managed to make it run without errors and publish it in Play Store as my first game. The player can see a part of the logo and guess the brand name using the given letters
But i would like to use the same template with new graphics and create a music quiz.
Instead of the logo guess game, the player will be able to listen a part of a song and guess the song's title.
The current project is getting the file names from a database stored in assets/databases folder.
So i managed to add start, pause and stop buttons in my activity_play.xml and succesfully created a mediaplayer in activityPlay.java file like:
public void music(View view) {
switch (view.getId()){
case R.id.button:
// Check if mediaPlayer is null. If true, we'll instantiate the MediaPlayer object
if(mediaPlayer == null){
mediaPlayer = MediaPlayer.create(this, R.raw.music);
}
// Then, register OnCompletionListener that calls a user supplied callback method onCompletion() when
// looping mode was set to false to indicate playback is completed.
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// Here, call a method to release the MediaPlayer object and to set it to null.
stopMusic();
}
});
// Next, call start() method on mediaPlayer to start playing the music.
mediaPlayer.start();
break;
case R.id.button2:
if(mediaPlayer != null) {
// Here, call pause() method on mediaPlayer to pause the music.
mediaPlayer.pause();
}
break;
case R.id.button3:
if(mediaPlayer != null){
// Here, call stop() method on mediaPlayer to stop the music.
mediaPlayer.stop();
// Call stopMusic() method
stopMusic();
}
break;
}
}
private void stopMusic() {
mediaPlayer.release();
mediaPlayer = null;
}
// Call stopMusic() in onStop() overridden method as well.
#Override
protected void onStop() {
super.onStop();
stopMusic();
}
The above code can succesfully play the music.mp3 file located in raw folder. The app i bought is using the following code to load the images and display them for each level:
String image_a = listDataBase.get(1);
String image_q = listDataBase.get(2);
if (isTrue == 1) {
String imgPath;
if (numImage == 0) {
imgPath = "file:///android_asset/logos/" + image_a;
} else {
imgPath = "file:///android_asset/logos/" + image_q;
}
Picasso.get().load(imgPath).into(imageView);
linearLayoutNullClick.setVisibility(View.VISIBLE);
recyclerViewKeys.setVisibility(View.GONE);
trueLogo = 2;
} else {
String imgPath = "file:///android_asset/logos/" + image_q;
Picasso.get().load(imgPath).into(imageView);
recyclerViewKeys.setVisibility(View.VISIBLE);
recyclerViewLogoKeys.setVisibility(View.VISIBLE);
}
So is it possible to use the same code and load the imgPath into mediaPlayer = MediaPlayer.create(this, R.raw.music);
I tried loading imgPath directly to mediaplayer like this but didn't work:
mediaPlayer = MediaPlayer.create(this, imgPath);
Then i tried:
private String audioPath;
audioPath = imgPath;
mediaPlayer = MediaPlayer.create(this, audioPath);
but also didn't work.
Tried many more methods i found on the web, but always i am missing something
As i said before i am a newbie in coding and programming so the solution probably will be very easy .
Anyone can help please?
Are you sure you are getting a audio path in your imgPath object?
Then you can try getting actual storage path from device using code mentioned
here
If you change the value in the database of pic_1.png with audio_1.mp3
then path will start like:
"file:///android_asset/logos/" + YOUR_AUDIO;
So are you sure audio exists in this path?
I have a project where I added a MediaPlayer in a custom Array Adapter and I make it take the Resource ID of the audio file from the Array List the problem is that I want to release the media player after the audio completes but every time I try to add release in OnCompletion and try to press a view while the media player plays a sound the app crashes .. I searched online and found a code but it gives me an error and I can't find the actual reason for such a crash.
that's the code for the on Click Listener and the Media player:
final MediaPlayer mediaPlayer = MediaPlayer.create(getContext(), currentWord.getVoiceResourceID());
// Wait for user's input by his click on the list's item to play the sound.
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Storing the return value of getVoiceResourceID() into mVoice.
// I think this line can be ignored so we call the method inside the creation of the Media Player.
// Creating our media player and put our track on it.
mediaPlayer.selectTrack(currentWord.getVoiceResourceID());
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.release();
}
});
}
};
I hope I could fix that problem.
i want to play mp4 video (which is playable for android) using videoview but it can't play the video.
my video is in sdcard folder,
can someone help me,
here is my code:
final VideoView vd = new VideoView(AboutActivity.this);
vd.setLayoutParams(new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, android.widget.LinearLayout.LayoutParams.MATCH_PARENT)); linevideo.addView(vd);
MediaController mediaController = new MediaController (this);
mediaController.setAnchorView (vd); vd.setMediaController (mediaController);
Uri video = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/media/vid.mp4");
vd.setVideoURI(video); vd.requestFocus (); vd.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp){
mp.setLooping(true);
vd.start ();
}
});
at first try to change
vd.setVideoURI(video);
to
vd.setVideoPath(video);
and check are you add below permission in manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I have seen that when declaring a videoView inside a layout; it sometimes doesn't show because is hidden behind some other component. To solve this you would have to add this line of code:
vd.setZOrderOnTop(true);
On other cases (although I'm not sure why this happens) it has worked for me to set the background of the videoView to transparent.
vd.setBackgroundColor(Color.TRANSPARENT);
You are on right track,
just use mp.start(); inside listener
vd.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp){
mp.setLooping(true);
**mp.start ();**
}
});
I am working on an app, wherein when a new activity is started, it should start playing a sound.
So I used mediaplayer to play the sound in oncreate and It worked fine. But when I tried to use soundpool instead, by loading and playing it in oncreate of the activity.
Its is not playing.
I choose soundpool, since its better than mediaplayer.
what might be the issue? doesn't soundpool work in oncreate?
Maybe you just need to put a sleep in the onCreate method.
I had pretty much same problem trying to write an app that would sometimes need to play a sound as soon as it woke up. Eventually after much trial and error I discovered that it was putting the error "sample NOT READY" in the log output. The problem was that loading a sound file happens asynchronously, and if you try to play the sound before it has loaded it fails.
There is supposedly a mechanism you can use called setOnLoadCompleteListener, but I've yet to see an example of how this is actually useful. In the example shown above from mirroredAbstraction (assuming it works as advertised) all that would happen if the sound is not loaded yet is that it would not play the sound, which is pretty much the same as what you have now.
If that example somehow magically "fixed" your problem then I would suggest that it was only because all the extra overhead in the two method calls basically give your sound time to load before it was played. You could probably have achieved the same outcome with a simple SystemClock.sleep(100) in your onCreate between the load the play.
Depending on the size of your sound you might need to lengthen the delay, but a bit of experimentation with differing delays should tell you how much you need.
Alternatively , you could override OnWindowFocusChanged to play the file when the Activity starts ...
Something like this ...
public class YourActivity extends Activity {
.
.
.
private Handler mHandler;
public void onCreate(Bundle savedInstanceState) {
.
.
.
this.mHandler = new Handler();
.
.
.
}
public void onWindowFocusChanged(boolean paramBoolean)
{
if (paramBoolean)
{
this.mHandler.postDelayed(new Runnable()
{
public void run()
{
// Refer to the answer above to create the play function for your soundfile ...
YourActivity.this.play("The sound from the sound pool");
}
}
, 1000L);
}
}
You can play it anywhere,
Ill demonstrate with a simple example
Create a method initializeSoundPool
private void initializeSoundPool(){
mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
soundID = mSoundPool.load(this, R.raw.glassbreak, 1);
}
Then create a method playFile
private void playFile(){
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
if (loaded) {
mSoundPool.play(soundID, volume, volume, 1, 0, 1f);
Log.e("Test", "Played sound");
}
}
Then in onCreate call them like this
private SoundPool mSoundPool;
private int soundID;
boolean loaded = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spxml);
initializeSoundPool();
playFile();
}
Or even better call initializeSoundPool in onCreate and then call playFile in onResume.
I'm wondering if there is any way to get an audio effect like the one here
in Java and/or Objective C. It is normally done in After Effects, but I want to create it on a smartphone. I know that the x axis is frequency and the y axis is volume. Can anyone help?
I'm not sure about iOS, but if you don't mind the extra space, Eclipse can handle a .mp3 file, and you can play it using the MediaPlayer class. As for creating the file, I'm not sure .raw has enough distinct sounds.
I played an mp3 in Android using a separate Music.java class and then calling it with mp3s in res/raw/*.mp3
import android.content.Context;
import android.media.MediaPlayer;
public class Music
{
private static MediaPlayer mp = null;
//Stop old song, play new one
public static void play(Context context, int resource)
{
stop(context);
if (Prefs.isMusic(context)) //is music on?
{
mp = MediaPlayer.create(context, resource);
mp.setLooping(true);
mp.start();
}//end if
}//end play method
//Stop the music
public static void stop(Context context)
{
if(mp != null)
{
mp.stop();
mp.release();
mp = null;
}//end if
}//end stop method
}//end class Music
and the calls in my Game.java file:
Music.play(this, R.raw.game);
Music.stop(this);