Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I play an audio file in Android?

Tags:

java

android

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:

  1. 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.
  2. 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??

like image 718
Natiya Avatar asked Jan 04 '12 18:01

Natiya


People also ask

How do I play audio files on Android?

To play audio or video files in Android, the Android multimedia framework includes the support of MediaPlayer APIs. So, by using MediaPlayer APIs, you can play audio/video files from your Android filesystem or play files from your Application's resource file or even you can stream audio/video files just like Spotify.

How do I get audio files to play?

Open File Manager and navigate to the folder where the audio file is located. Drag the audio file icon from File Manager and drop it on the Audio main window. The Selected file is opened. If Automatically play audio file on Open is selected in the Options-Play dialog box, the audio file starts playing.

What class in Android can play audio?

One of the most important components of the media framework is the MediaPlayer class. An object of this class can fetch, decode, and play both audio and video with minimal setup.

How can we play audio and video file through Android?

Android App Development for Beginners Android provides many ways to control playback of audio/video files and streams. One of this way is through a class called MediaPlayer. MediaPlayer mediaPlayer = MediaPlayer.


5 Answers

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.

like image 160
manjusg Avatar answered Oct 16 '22 13:10

manjusg


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?

like image 41
Force Avatar answered Oct 16 '22 15:10

Force


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();
        }

    });

}
like image 3
BobMcboberson Avatar answered Oct 16 '22 14:10

BobMcboberson


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);
like image 1
Venki WAR Avatar answered Oct 16 '22 13:10

Venki WAR


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();
        }

    }
like image 1
Programmerabc Avatar answered Oct 16 '22 14:10

Programmerabc