Android java audio source

How do I play an audio file in 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; > > 
[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??

Источник

Работа с потоковым аудио

Причин ошибки может быть две: слишком маленький буфер и недопустимый формат. Первого нужно избегать вызовом getMinBufferSize() . Второго, на самом деле, им же.

getMinBufferSize()

Этот статический метод выдаёт минимальный размер внутреннего буфера, при котором объект AudioRecord сможет работать. Параметры имеют тот же смысл, что и для конструктора. Следует заметить, что использование именно этой величины для записи — не лучшая идея. Если система будет ещё чем-то занята, то программа всё равно может не успевать считывать все данные подряд, и в записи будут дырки. Мне встречался совет брать размер в десять раз больше.

Получение списка форматов

Метод getMinBufferSize() имеет приятную особенность — ругаться на недопустимые для данного устройства параметры, возвращая ERROR_BAD_VALUE или ERROR . Это означает, что перебирая все возможные сочетания, можно узнать, какие форматы поддерживает устройство.

int[] rates = ; int[] chans = ; int[] encs = ; for(int enc : encs) < for(int ch : chans) < for(int rate : rates) < int t = AudioRecord.getMinBufferSize(rate, ch, enc); if((t != AudioRecord.ERROR) && (t != AudioRecord.ERROR_BAD_VALUE)) < // добавляем формат >> > >
Считывание данных
  • read(byte[] audioData, int offsetInBytes, int sizeInBytes)
  • read(short[] audioData, int offsetInShorts, int sizeInShorts)
  • read(ByteBuffer audioBuffer, int sizeInBytes)
Читайте также:  Bitrix apache php fpm

Важно: метод блокирует вызывающий поток до тех пор, пока не считает запрошенное количество данных. Если во внутреннем буфере их недостаточно, то read() будет ожидать, пока они придут от микрофона. Поэтому метод следует вызывать из отдельного потока, иначе приложение будет висеть.

Подход, отход, фиксация

Чтобы программа могла получать данные от микрофона, нужно указать в файле AndroidManifest,xml соответствующее разрешение:

Чтобы начать запись, нужно вызвать метод startRecording() , а чтобы закончить — stop() . Запускать и останавливать запись можно сколько угодно раз.

После того, как работа с объектом закончена, следует вызвать метод release() . Он освободит все системные ресурсы, захваченные объектом. После этого объект нельзя использовать, а ссылающуюся на него переменную следует установить в null .

Важно: эти три метода, в отличие от упоминавшихся ранее, выбросят IllegalStateException , если их вызвать для неинициализированного (ну и слово. ) объекта или не в том порядке. Поэтому обращаться с ними нужно «аккуратно», т.е. через блок try .

Пример использования

Приведённый ниже класс делает всё то, о чём сказано выше. Кроме того, он посылает зарегистрированным у него Handler -ам сообщения о принятых данных. Эти данные будут обрабатываться в другом потоке, поэтому, чтобы не затереть ещё не обработанные данные новыми, использован циклический буфер.

В коде использован класс AudioFormatInfo . Он представляет собой POJO с тремя полями, описывающими формат записи: sampleRateInHz , channelConfig и audioFormat .

package com.MyCompany; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Handler; import android.os.Process; //AudioFormatInfo - POJO с полями sampleRateInHz, channelConfig и audioFormat public class AudioReciever implements Runnable < private boolean mIsRunning; private Listhandlers; private AudioFormatInfo format; private AudioRecord mRecord; private final int BUFF_COUNT = 32; public AudioReciever(AudioFormatInfo format) < this.format = format; handlers = new ArrayList(); mIsRunning = true; mRecord = null; > public void addHandler(Handler handler) < handlers.add(handler); >public void stop() < mIsRunning = false; >@Override public void run() < // приоритет для потока обработки аудио Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO); mIsRunning = true; int buffSize = AudioRecord.getMinBufferSize(format.getSampleRateInHz(), format.getChannelConfig(), format.getAudioFormat()); if(buffSize == AudioRecord.ERROR) < System.err.println("getMinBufferSize returned ERROR"); return; >if(buffSize == AudioRecord.ERROR_BAD_VALUE) < System.err.println("getMinBufferSize returned ERROR_BAD_VALUE"); return; >// здесь работаем с short, поэтому требуем 16-bit if(format.getAudioFormat() != AudioFormat.ENCODING_PCM_16BIT) < System.err.println("unknown format"); return; >// циклический буфер буферов. Чтобы не затереть данные, // пока главный поток их обрабатывает short[][] buffers = new short[BUFF_COUNT][buffSize >> 1]; mRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, format.getSampleRateInHz(), format.getChannelConfig(), format.getAudioFormat(), buffSize * 10); if(mRecord.getState() != AudioRecord.STATE_INITIALIZED) < System.err.println("getState() != STATE_INITIALIZED"); return; >try < mRecord.startRecording(); >catch(IllegalStateException e) < e.printStackTrace(); return; >int count = 0; while(mIsRunning) < int samplesRead = mRecord.read(buffers[count], 0, buffers[count].length); if(samplesRead == AudioRecord.ERROR_INVALID_OPERATION) < System.err.println("read() returned ERROR_INVALID_OPERATION"); return; >if(samplesRead == AudioRecord.ERROR_BAD_VALUE) < System.err.println("read() returned ERROR_BAD_VALUE"); return; >// посылаем оповещение обработчикам sendMsg(buffers[count]); count = (count + 1) % BUFF_COUNT; > try < try < mRecord.stop(); >catch(IllegalStateException e) < e.printStackTrace(); return; >> finally < // освобождаем ресурсы mRecord.release(); mRecord = null; >> private void sendMsg(short[] data) < for(Handler handler : handlers) < handler.sendMessage(handler.obtainMessage(MSG_DATA, data)); >> >

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

High-level library for efficient playback of sounds and music on Android

Читайте также:  List minus list python

License

delight-im/Android-Audio

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

High-level library for efficient playback of sounds and music on Android

  • Include one of the JARs in your libs folder
  • or
  • Copy the Java package to your project’s source folder
  • or
  • Create a new library project from this repository and reference it in your project

Playing music and one-off sound files

MusicManager.getInstance().play(MyActivity.this, R.raw.my_sound); 

Playing sounds (frequently and fast)

class MyActivity extends Activity < private SoundManager mSoundManager; @Override protected void onResume() < super.onResume(); int maxSimultaneousStreams = 3; mSoundManager = new SoundManager(this, maxSimultaneousStreams); mSoundManager.start(); mSoundManager.load(R.raw.my_sound_1); mSoundManager.load(R.raw.my_sound_2); mSoundManager.load(R.raw.my_sound_3); >private void playSomeSound() < if (mSoundManager != null) < mSoundManager.play(R.raw.my_sound_2); >> @Override protected void onPause() < super.onPause(); if (mSoundManager != null) < mSoundManager.cancel(); mSoundManager = null; >> > 

All contributions are welcome! If you wish to contribute, please create an issue first so that your feature, problem or question can be discussed.

Copyright (c) delight.im Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

About

High-level library for efficient playback of sounds and music on Android

Источник

Streaming Audio from A URL in Android using MediaPlayer?

I’ve been trying to stream mp3’s over http using Android’s built in MediaPlayer class. The documentation would suggest to me that this should be as easy as :

MediaPlayer mp = new MediaPlayer(); mp.setDataSource(URL_OF_FILE); mp.prepare(); mp.start(); 

However I am getting the following repeatedly. I have tried different URLs as well. Please don’t tell me that streaming doesn’t work on mp3’s.

E/PlayerDriver( 31): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported W/PlayerDriver( 31): PVMFInfoErrorHandlingComplete E/MediaPlayer( 198): error (1, -4) E/MediaPlayer( 198): start called in state 0 E/MediaPlayer( 198): error (-38, 0) E/MediaPlayer( 198): Error (1,-4) E/MediaPlayer( 198): Error (-38,0) 

A few questions: (1) which SDK version are you using? (2) Which device(s) are you testing on? This works fine on SDK 2.0.1, testing on a Droid.

Hi Roman, thanks for taking the time. I am trying this against 1.6 and I am using an HTC Hero. I will try it on 2.01 in in light of your comments but it would be a ridiculous outcome if this only worked on 2.x and and above devices out of he box.

Читайте также:  What is php include and require

Just tried it on a 2.01 emulator. Doesn’t work unfortunately. I am intrigued to try this against a real 1.6 device and a real 2.01 device. I’m in Google testing on the 4th. Maybe I’ll have to wait till then. I’d prefer not to have to though.

I don’t suspect 2.0 vs. 2.0.1 will make any difference, but emulator vs. a live device may make a difference. I’m surprised this didn’t work on the Hero. I’ll look into it and see if I can get a better answer. Oh also, just as a sanity check, you should make sure you’ve requested the INTERNET permission in the manifest.

Hey just outta discussion I have a question. If I use mp.setDataSource(URL_OF_FILE); We do not need to save any file for the audio streaming. Isn’t it? So that way its the best way to stream audio from any location. Any ideas?

7 Answers 7

simple Media Player with streaming example.For xml part you need one button with id button1 and two images in your drawable folder with name button_pause and button_play and please don’t forget to add the internet permission in your manifest.

public class MainActivity extends Activity < private Button btn; /** * help to toggle between play and pause. */ private boolean playPause; private MediaPlayer mediaPlayer; /** * remain false till media is not completed, inside OnCompletionListener make it true. */ private boolean intialStage = true; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button) findViewById(R.id.button1); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); btn.setOnClickListener(pausePlay); >@Override public boolean onCreateOptionsMenu(Menu menu) < // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; >private OnClickListener pausePlay = new OnClickListener() < @Override public void onClick(View v) < // TODO Auto-generated method stub // TODO Auto-generated method stub if (!playPause) < btn.setBackgroundResource(R.drawable.button_pause); if (intialStage) new Player() .execute("http://www.virginmegastore.me/Library/Music/CD_001214/Tracks/Track1.mp3"); else < if (!mediaPlayer.isPlaying()) mediaPlayer.start(); >playPause = true; > else < btn.setBackgroundResource(R.drawable.button_play); if (mediaPlayer.isPlaying()) mediaPlayer.pause(); playPause = false; >> >; /** * preparing mediaplayer will take sometime to buffer the content so prepare it inside the background thread and starting it on UI thread. * @author piyush * */ class Player extends AsyncTask  < private ProgressDialog progress; @Override protected Boolean doInBackground(String. params) < // TODO Auto-generated method stub Boolean prepared; try < mediaPlayer.setDataSource(params[0]); mediaPlayer.setOnCompletionListener(new OnCompletionListener() < @Override public void onCompletion(MediaPlayer mp) < // TODO Auto-generated method stub intialStage = true; playPause=false; btn.setBackgroundResource(R.drawable.button_play); mediaPlayer.stop(); mediaPlayer.reset(); >>); mediaPlayer.prepare(); prepared = true; > catch (IllegalArgumentException e) < // TODO Auto-generated catch block Log.d("IllegarArgument", e.getMessage()); prepared = false; e.printStackTrace(); >catch (SecurityException e) < // TODO Auto-generated catch block prepared = false; e.printStackTrace(); >catch (IllegalStateException e) < // TODO Auto-generated catch block prepared = false; e.printStackTrace(); >catch (IOException e) < // TODO Auto-generated catch block prepared = false; e.printStackTrace(); >return prepared; > @Override protected void onPostExecute(Boolean result) < // TODO Auto-generated method stub super.onPostExecute(result); if (progress.isShowing()) < progress.cancel(); >Log.d("Prepared", "//" + result); mediaPlayer.start(); intialStage = false; > public Player() < progress = new ProgressDialog(MainActivity.this); >@Override protected void onPreExecute() < // TODO Auto-generated method stub super.onPreExecute(); this.progress.setMessage("Buffering. "); this.progress.show(); >> @Override protected void onPause() < // TODO Auto-generated method stub super.onPause(); if (mediaPlayer != null) < mediaPlayer.reset(); mediaPlayer.release(); mediaPlayer = null; >> 

Источник

Оцените статью