안드로이드 벨소리를 재생시키기 위해서는 우선 MediaPlayer함수를 상속받고 그것의 StreamType을 선언하고 start하고 stop하는 방법이 있다.
우선. start하는 곳까지 알아보자.
public void Test(){ MediaPlayer mAudio = new MediaPlayer(); // 음원 파일 패스 String path = "/system/media/audio/ringtones/xxxx.ogg" mAudio.setDataSource(path); // path집어 넣어준다. 이때 시스템 음원을 사용할 수도 앱안에 넣어서 실행할수도 있음 mAudio.setAudioType(StreamType); // StreamType은 AudioManager.STREAM_RING, AudioManager.STREAM_MUSIC, AudioManager.STREAM_VOICE_CALL 등 다양하다. 골라서 쓰면 될 듯
mAudio.start(); 음원 스타트 }
// 참고로 멈추는 것은 // if(mAudio.isPlaying()) // mAudio.stop(); // 위와같이 해주면 끝
하지만 Media가 돌아갈 때의 lifeCycle을 모르고 개발을 한다는 것도 어불성설이다.
위의 라이프사이클을 통해서 음원이 어떤식으로 초기화 > 실행 > 멈춤 > 완료 되는 지 알아봐야 한다.
MediaPlayer class can be used to control playback of audio/video files and streams. An example on how to use the methods in this class can be found in VideoView.
For more information about how to use MediaPlayer, read the Media Playback developer guide.
State Diagram
Playback control of audio/video files and streams is managed as a state machine. The following diagram shows the life cycle and the states of a MediaPlayer object driven by the supported playback control operations. The ovals represent the states a MediaPlayer object may reside in. The arcs represent the playback control operations that drive the object state transition. There are two types of arcs. The arcs with a single arrow head represent synchronous method calls, while those with a double arrow head represent asynchronous method calls.
From this state diagram, one can see that a MediaPlayer object has the following states:
When a MediaPlayer object is just created using new or after reset() is called, it is in the Idle state; and after release() is called, it is in the Endstate. Between these two states is the life cycle of the MediaPlayer object.
There is a subtle but important difference between a newly constructed MediaPlayer object and the MediaPlayer object after reset() is called. It is a programming error to invoke methods such as getCurrentPosition(), getDuration(), getVideoHeight(), getVideoWidth(),setAudioStreamType(int), setLooping(boolean), setVolume(float, float), pause(), start(), stop(), seekTo(int), prepare()or prepareAsync() in the Idle state for both cases. If any of these methods is called right after a MediaPlayer object is constructed, the user supplied callback method OnErrorListener.onError() won't be called by the internal player engine and the object state remains unchanged; but if these methods are called right after reset(), the user supplied callback method OnErrorListener.onError() will be invoked by the internal player engine and the object will be transfered to the Error state.
It is also recommended that once a MediaPlayer object is no longer being used, call release() immediately so that resources used by the internal player engine associated with the MediaPlayer object can be released immediately. Resource may include singleton resources such as hardware acceleration components and failure to call release() may cause subsequent instances of MediaPlayer objects to fallback to software implementations or fail altogether. Once the MediaPlayer object is in the End state, it can no longer be used and there is no way to bring it back to any other state.
Furthermore, the MediaPlayer objects created using new is in the Idle state, while those created with one of the overloaded convenient createmethods are NOT in the Idle state. In fact, the objects are in the Prepared state if the creation using create method is successful.
In general, some playback control operation may fail due to various reasons, such as unsupported audio/video format, poorly interleaved audio/video, resolution too high, streaming timeout, and the like. Thus, error reporting and recovery is an important concern under these circumstances. Sometimes, due to programming errors, invoking a playback control operation in an invalid state may also occur. Under all these error conditions, the internal player engine invokes a user supplied OnErrorListener.onError() method if an OnErrorListener has been registered beforehand via setOnErrorListener(android.media.MediaPlayer.OnErrorListener).
It is important to note that once an error occurs, the MediaPlayer object enters the Error state (except as noted above), even if an error listener has not been registered by the application.
In order to reuse a MediaPlayer object that is in the Error state and recover from the error, reset() can be called to restore the object to its Idlestate.
It is good programming practice to have your application register a OnErrorListener to look out for error notifications from the internal player engine.
IllegalStateException is thrown to prevent programming errors such as calling prepare(), prepareAsync(), or one of the overloadedsetDataSource methods in an invalid state.
An IllegalStateException is thrown if setDataSource() is called in any other state.
It is good programming practice to always look out for IllegalArgumentException and IOException that may be thrown from the overloaded setDataSource methods.
A MediaPlayer object must first enter the Prepared state before playback can be started.
There are two ways (synchronous vs. asynchronous) that the Prepared state can be reached: either a call to prepare() (synchronous) which transfers the object to the Prepared state once the method call returns, or a call to prepareAsync() (asynchronous) which first transfers the object to the Preparing state after the call returns (which occurs almost right way) while the internal player engine continues working on the rest of preparation work until the preparation work completes. When the preparation completes or when prepare() call returns, the internal player engine then calls a user supplied callback method, onPrepared() of the OnPreparedListener interface, if an OnPreparedListener is registered beforehand via setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener).
It is important to note that the Preparing state is a transient state, and the behavior of calling any method with side effect while a MediaPlayer object is in the Preparing state is undefined.
An IllegalStateException is thrown if prepare() or prepareAsync() is called in any other state.
While in the Prepared state, properties such as audio/sound volume, screenOnWhilePlaying, looping can be adjusted by invoking the corresponding set methods.
To start the playback, start() must be called. After start() returns successfully, the MediaPlayer object is in the Started state. isPlaying()can be called to test whether the MediaPlayer object is in the Started state.
While in the Started state, the internal player engine calls a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback method if a OnBufferingUpdateListener has been registered beforehand via setOnBufferingUpdateListener(OnBufferingUpdateListener). This callback allows applications to keep track of the buffering status while streaming audio/video.
Calling start() has not effect on a MediaPlayer object that is already in the Started state.
Playback can be paused and stopped, and the current playback position can be adjusted. Playback can be paused via pause(). When the call topause() returns, the MediaPlayer object enters the Paused state. Note that the transition from the Started state to the Paused state and vice versa happens asynchronously in the player engine. It may take some time before the state is updated in calls to isPlaying(), and it can be a number of seconds in the case of streamed content.
Calling start() to resume playback for a paused MediaPlayer object, and the resumed playback position is the same as where it was paused. When the call to start() returns, the paused MediaPlayer object goes back to the Started state.
Calling pause() has no effect on a MediaPlayer object that is already in the Paused state.
Calling stop() stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state.
Once in the Stopped state, playback cannot be started until prepare() or prepareAsync() are called to set the MediaPlayer object to thePrepared state again.
Calling stop() has no effect on a MediaPlayer object that is already in the Stopped state.
The playback position can be adjusted with a call to seekTo(int).
Although the asynchronuous seekTo(int) call returns right way, the actual seek operation may take a while to finish, especially for audio/video being streamed. When the actual seek operation completes, the internal player engine calls a user supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener has been registered beforehand viasetOnSeekCompleteListener(OnSeekCompleteListener).
Please note that seekTo(int) can also be called in the other states, such as Prepared, Paused and PlaybackCompleted state.
Furthermore, the actual current playback position can be retrieved with a call to getCurrentPosition(), which is helpful for applications such as a Music player that need to keep track of the playback progress.
When the playback reaches the end of stream, the playback completes.
If the looping mode was being set to truewith setLooping(boolean), the MediaPlayer object shall remain in the Started state.
If the looping mode was set to false , the player engine calls a user supplied callback method, OnCompletion.onCompletion(), if a OnCompletionListener is registered beforehand via setOnCompletionListener(OnCompletionListener). The invoke of the callback signals that the object is now in the PlaybackCompleted state.
While in the PlaybackCompleted state, calling start() can restart the playback from the beginning of the audio/video source
아마 위에서 AsyncPrepare()때문에 추후에 prepare되는것때문에 작동이 안되는가 하는 짐작도 듭니다.
async를 빼보고 그냥 prepare만 해보세요.
MediaPlayer로 음악을 Start()하기전에 Prepare()를 하는데 이거 전에 StreamType을 변경하면 됩니다.
아래는 예제 소스입니다.
mp.setAudioStreamType(AudioManager.STREAM_RING);
Log.i("onCreate","setAudioStreamType");
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("onCreate","prepare");
mp.start();
Log.i("onCreate","start");
=======================
=======================
=======================
출처: http://cookzy.tistory.com/927
Cocos2d-X로 멀티플랫폼 게임을 개발중입니다.
iOS에서는 문제 없었지만 안드로이드로 넘어오면서 몇가지 문제가 생깁니다.
그나마 main java소소에서 몇줄 추가로 간단하게 해결할 수 있습니다.
다음 소스를 원하시는 곳에 추가하시면 됩니다.
주로 onCreate() 또는 onStart()에 넣으시면 됩니다. 그럼 현재 모드를 확인해서 Cocos2d-X로 Jni를 이용해서 음소거를 시켜주면 됩니다. 게임 음원 출력 프로세스에서 bool형의 isMute 변수를 만들어서 toggle해주는 방식을 사용하시길 추천드립니다.
대부분의 IDE가이 작업을 수행하지만, 사용자가하지 않는 경우 다음과 같은 import 문이 있습니다.
import android.os.Vibrator;
진동이 발생하는 활동에서 이것을 확인하십시오.
주어진 시간 동안 진동하는 법
대부분의 경우, 미리 정해진 짧은 시간 동안 장치를 진동시키고 싶을 것입니다. vibrate(long milliseconds) 방법을 사용하여이 작업을 수행 할 수 있습니다. 다음은 간단한 예입니다.
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
v.vibrate(400);
그게 다 간단 해!
무한정 진동하는 법
장치가 무기한 계속 진동하기를 원할 수도 있습니다. 이를 위해 vibrate(long[] pattern, int repeat) 메서드를 사용합니다.
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 1000};
// The '0' here means to repeat indefinitely
// '0' is actually the index at which the pattern keeps repeating from (the start)
// To repeat the pattern from any other point, you could increase the index, e.g. '1'
v.vibrate(pattern, 0);
진동을 중단 할 준비가되면 cancel() 메소드를 호출하면됩니다.
v.cancel();
진동 패턴을 사용하는 방법
좀 더 맞춤화 된 진동을 원한다면 자신 만의 진동 패턴을 만들 수 있습니다.
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Each element then alternates between vibrate, sleep, vibrate, sleep...
long[] pattern = {0, 100, 1000, 300, 200, 100, 500, 200, 100};
// The '-1' here means to vibrate once, as '-1' is out of bounds in the pattern array
v.vibrate(pattern, -1);
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Output yes if can vibrate, no otherwise
if (v.hasVibrator()) {
Log.v("Can Vibrate", "YES");
} else {
Log.v("Can Vibrate", "NO");
}
두 번째로, 애플리케이션에 진동을 허용했는지 확인하십시오! 첫 번째 지점을 다시 참조하십시오.
Question
Android 애플리케이션을 작성했습니다. 이제 특정 동작이 발생할 때 장치를 진동 상태로 만들려고합니다. 어떻게해야합니까?
위의 답변은 완벽합니다. 그러나 버튼 클릭시 정확히 두 번 내 앱을 진동시키고 싶었고이 작은 정보가 여기에 누락되어 나와 같은 미래의 독자를 위해 게시했습니다. :)
우리는 위에서 언급 한대로 따라야 만하며, 유일한 변화는 아래와 같이 진동 패턴입니다.
long[] pattern = {0, 100, 1000, 300};
v.vibrate(pattern, -1); //-1 is important
이것은 정확하게 두 번 진동합니다. 우리는 이미 0은 지연을 의미하는 것으로 100은 처음으로 100MS로 진동하고, 다음에 1000MS의 지연이 발생하고 300MS에 대해 다시 진동하는 것을 알 수 있습니다.
하나는 계속적으로 딜레이와 진동을 언급 할 수 있지만 (예 : 0, 100, 1000, 300, 1000, 3 진동은 300 등), @ Dave의 단어는 책임감있게 사용하십시오. :)
또한 반복 매개 변수가 -1로 설정되어 진동이 패턴에서 언급 된 것과 정확히 일치 함을 의미합니다. :)
1.
AudioManager aManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
그리고나서 밸/진동/무음 모드는 다음과 같이 바꾸시면 됩니다.
1.
aManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
2.
aManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
3.
aManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);