상세 컨텐츠

본문 제목

[android] Android 진동, 벨소리 재생, 미디어 재생, 내장 스피커 재생 관련

스마트기기개발관련/안드로이드 개발

by AlrepondTech 2018. 3. 12. 17:30

본문

반응형
728x170



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: http://aldehyde7.tistory.com/138



원래 포스팅 순서가 이 글을 먼저 올리고,

볼륨조절 글을 올려야 순서가 맞지만 

깜빡하고, 늦게 올림 -0-;;;

이 글의 내용의 출발은 벨소리 재생이었다.

디바이스에 내장된 Ringtone을 재생하는 방법을 찾기 위해서였다.


여기저기 찾아본 결과 Ringtone과 RingtoneManager 클래스를 가지고 하면된다고 나와있지만,

자세한 코드는 찾기 힘들었다.

그래서 해당 클래스를 조금 깊게 보니 MediaPlayer 클래스를 통해서 재생을 하는 것이었다.

MediaPlayer 클래스는 특정 미디어를 재생할 때, 스트리밍 타입을 가지고 어떻게(?) 재생할 지를

결정하게 된다. 

예를들어 벨소리(Ringtone)의 경우 외장 스피커로 재생이 되어야 사용자가 전화가 온지 알 수 있을 것이며,

통화의 경우 기본으로 내장스피커를 통해서 통화 내용이 재생되어야 할 것이다.

이같은 것을 스트리밍 타입으로 두어 재생을 하게 된다.

볼륨조절 관련 포스팅글 소스랑 거의 같으니 Play와 Stop에 관한 내용만 보면 된다.


001.package kr.ac.inha.eslab.aldehyde7;
002. 
003.import android.app.Activity;
004.import android.content.Context;
005.import android.media.AudioManager;
006.import android.media.MediaPlayer;
007.import android.media.RingtoneManager;
008.import android.net.Uri;
009.import android.os.Bundle;
010.import android.util.Log;
011.import android.view.View;
012.import android.view.View.OnClickListener;
013.import android.widget.AdapterView;
014.import android.widget.AdapterView.OnItemSelectedListener;
015.import android.widget.ArrayAdapter;
016.import android.widget.Button;
017.import android.widget.Spinner;
018. 
019.public class VolumeTest extends Activity implements OnItemSelectedListener, OnClickListener {
020./** Called when the activity is first created. */
021. 
022.// Spinner
023.Spinner spn;
024. 
025.// MediaPlayer
026.MediaPlayer mAudio = null;
027.boolean isPlay = false;
028. 
029.int StreamType = 0;
030. 
031.Button btnPlay;
032. 
033.@Override
034.public void onCreate(Bundle savedInstanceState) {
035.super.onCreate(savedInstanceState);
036.setContentView(R.layout.main);
037. 
038.// Spinner -->
039.spn = (Spinner)findViewById(R.id.Spinner01);
040.ArrayAdapter<charsequence> adapter = ArrayAdapter.createFromResource(thisR.array.UserList, android.R.layout.simple_spinner_item);
041.adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); 
042.spn.setAdapter(adapter);
043.spn.setOnItemSelectedListener(this);
044.// <-- Spinner
045. 
046.btnPlay = (Button) findViewById(R.id.Button01);
047. 
048.btnPlay.setOnClickListener(this);
049. 
050.}
051. 
052.public void PlayTest()
053.{
054.try{
055.mAudio = new MediaPlayer();
056.// 디바이스에 설정된 벨소리를 사용할 때
057.//Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
058.//Log.d("URI", "Ringtone URI : " + alert.toString()); // content://settings/system/ringtone
059.//mAudio.setDataSource(alert.toString());
060.// 벨소리로 재생 할 음원 파일 패스
061.String path = "/system/media/audio/ringtones/Red_Beats.ogg";
062.mAudio.setDataSource(path);;
063. 
064.// 벨소리
065.//mAudio.setAudioStreamType(AudioManager.STREAM_RING);
066.// 미디어
067.//mAudio.setAudioStreamType(AudioManager.STREAM_MUSIC);
068.// 전화(수신 스피커)
069.//mAudio.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
070. 
071.// Spinner에서 설정한 스트리밍 타입
072.mAudio.setAudioStreamType(StreamType);
073. 
074.mAudio.setLooping(true);
075.mAudio.prepare();
076.}
077.catch (Exception e) {
078. 
079.}
080. 
081.mAudio.start();
082. 
083.isPlay = true;
084. 
085. 
086. 
087.}
088.public void StopTest()
089.{
090.if(mAudio.isPlaying())
091.{
092.mAudio.stop();
093.isPlay = false;
094.}
095.else
096.{
097.// not playing
098.}
099.}
100. 
101.@Override
102.public void onItemSelected(AdapterView<!--?--> arg0, View arg1, int arg2,
103.long arg3) {
104.switch(arg2)
105.{
106.case 0:
107.{
108.StreamType = AudioManager.STREAM_RING;
109.break;
110.}
111.case 1:
112.{
113.StreamType = AudioManager.STREAM_MUSIC;
114.break;
115.}
116.case 2:
117.{
118.StreamType = AudioManager.STREAM_VOICE_CALL;
119.break;
120.}
121.}      
122.// TODO Auto-generated method stub
123. 
124.}
125. 
126.@Override
127.public void onNothingSelected(AdapterView<!--?--> arg0) {
128.// TODO Auto-generated method stub
129. 
130.}
131. 
132.@Override
133.public void onClick(View arg0) {
134.// TODO Auto-generated method stub
135.switch(arg0.getId())
136.{
137.case R.id.Button01:
138.{
139.Log.d("BTN""PLAY/STOP");
140.if(!isPlay)
141.{
142.PlayTest();
143.}
144.else
145.{
146.StopTest();
147.}
148. 
149.break;
150.}      
151.}
152.}
153.</charsequence>


출처: http://aldehyde7.tistory.com/138 [Dynamic Life]


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: https://m.blog.naver.com/PostView.nhn?blogId=ijoos&logNo=60178336636&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F



안드로이드 벨소리를 재생시키기 위해서는 우선 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을 모르고 개발을 한다는 것도 어불성설이다.

위의 라이프사이클을 통해서 음원이 어떤식으로 초기화 > 실행 > 멈춤 > 완료 되는 지 알아봐야 한다.

 

 

public classMediaPlayerextends Object
java.lang.Object
   ↳android.media.MediaPlayer
Class Overview

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.

Topics covered here are:

  1. State Diagram
  2. Valid and Invalid States
  3. Permissions
  4. Register informational and error callbacks
Developer Guides

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.


요것을 읽어보면 제일 좋을 듯.

http://developer.android.com/reference/android/media/MediaPlayer.html

 

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.
  • Calling setDataSource(FileDescriptor), or setDataSource(String), or setDataSource(Context, Uri), orsetDataSource(FileDescriptor, long, long) transfers a MediaPlayer object in the Idle state to the Initialized 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 StartedPausedPrepared 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 PreparedPaused 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

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: https://www.androidpub.com/1910654


MediaPlayer a = MediaPlayer.create(Context context, int resid)
a.start();

 

이렇게 쓰면은 핸드폰에서 이걸 실행시켰을때 미디어볼륨으로 들어가는대요

벨소리 볼륨으로 바꾸게 하는 방법이 없을까요

 

MediaPlayer a = MediaPlayer.create(Activity.this, R.raw.a);
     try{
      a.prepareAsync();
      a.setAudioStreamType(2);  // 2  : AudioManager.STREAM_RING
      a.prepare();
     }catch(Exception e){
      er.start();

     }

 

이렇게 설정했는대 그래도 미디어볼륨으로 들어가더라구요.

방법이 없겠습니까??

------------------------------------------------------------------------------------------------------------------------

아마 위에서 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해주는 방식을 사용하시길 추천드립니다. 

//------------------------------------------------------------------------------------------------

// 단말기가 진동모드/음소거모드 일경우에는 mute를 시켜주거나 적절한 처리를 해준다..

AudioManager audioManager =  (AudioManager)getSystemService(Context.AUDIO_SERVICE);

if(audioManager.getRingerMode()== AudioManager.RINGER_MODE_NORMAL) 

       // 사운드 재생         

        NativeSetSoundMuteOff();

        System.out.println("COCOS2DX : SOUND ON ");

}

else

{

        NativeSetSoundMuteOn();

        System.out.println("COCOS2DX : SOUND OFF");

  }

다음 함수들을 이용해서 실제로 게임에 상태를 음소거로 변경해주면 됩니다.

private native int NativeSetSoundMuteOn();

private native int NativeSetSoundMuteOff();


매일밤 늦게까지 고생하시는 개발자분들에게 조금이나마 도움이되었으면 하는 바람입니다.

그리고 남는 시간에는 자기개발을....



출처: http://cookzy.tistory.com/927 [우리가 사는 세상]



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: https://www.androidpub.com/?mid=android_dev_qna&page=6&document_srl=250357


간단할 수 있을 것이라고 생각하는데요,,,

안드로이드 처음 접해봐서 접근을 못하고 있습니다.. 많은 도움 부탁드리겠습니다.

현재 벨/ 진동/ 무음을 사용자의 이벤트에 따라서 전환하는 것을 구현하려고 하고 있습니다.

벨/ 진동 / 무음으로 전환하는 방법과 API를 알려주시면 감사하겠습니다..



-------------------------------------------------------------------------------------------------------------------------------

밸 진동 무음 전환은 AudioManager 를 통해서 합니다. new 를 해주실 필요는 없고 context 에서 메니저를 아래와같이 받아오시면 됩니다.

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


댓글
2010.04.08 16:53:06
코파카바나
아 감사합니다.^^ㅋ
혹시 벨/진동/무음 전환하는 테스트는 에뮬에서는 불가능 한가요?
댓글
2010.04.08 17:02:45
id: 엥꼬엥꼬

당연히 에뮬로 진동을 느낄수는 없지만 ^^; notification 영역에 무음일때와 진동일때 뜨는 아이콘으로 확인은 가능합니다


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: https://www.androidpub.com/1827001



local service의 멀티스레드에서 동작하는 부분입니다.
MediaPlayer 혼자는 잘 동작합니다. 

그러나, 진동과 함께 사운드 연주를 하려고 해보니 안되는군요.
진동은 무조건 안되고, 진동 코드가 들어가니 음악도 전혀 안나옵니다. 

참고로,

되는 코드 : 음악이 잘 나옴 
음악만 코드
MediaPlayer mp = MediaPlayer.create(service, R.raw.position_pass);
mp.setOnCompletionListener(this);
mp.start(); 

안되는 코드 : 진동만 코드
진동도 되지 않음 
Vibrator vib = (Vibrator) service.getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(1000);
//MediaPlayer mp = MediaPlayer.create(service, R.raw.position_pass);
//mp.setOnCompletionListener(this);
//mp.start(); 

안되는 코드 : 진동과 음악 
진동도 안되고 음악도 안나옴 
Vibrator vib = (Vibrator) service.getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(1000);
MediaPlayer mp = MediaPlayer.create(service, R.raw.position_pass);
mp.setOnCompletionListener(this);
mp.start(); 


--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

진동 퍼미션을 안 주었네요. 퍼미션을 줘서 해봐야겠네요.

그런데, 로그캣에 에러도 안뜨고 소리도 안나오고 진동도 안되는 것은 좀 그렇네요 ^^; 


댓글
2011.11.04 15:48:12
지능도시

진동 퍼미션을 주니 음악도 잘 나오네요. 


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: https://code.i-harness.com/ko/q/d4dd82



진동 코드를 구현하기 전에 응용 프로그램에 진동을 허용해야합니다.

<uses-permission android:name="android.permission.VIBRATE"/>

이 행을 AndroidManifest.xml 파일에 포함해야합니다.

진동 라이브러리 가져 오기

대부분의 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);

더 복잡한 진동

보다 포괄적 인 햅틱 피드백 범위를 제공하는 여러 SDK가 있습니다. 특수 효과 용으로 사용되는 것은 Immersion의 Android 용 햅틱 개발 플랫폼입니다.

문제 해결

장치가 진동하지 않으면 먼저 진동이 발생하는지 확인하십시오.

// 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로 설정되어 진동이 패턴에서 언급 된 것과 정확히 일치 함을 의미합니다. :)




<uses-permission android:name="android.permission.VIBRATE"/>

<manifest> 태그와 <application> 태그 외부에 추가되어야합니다.




다음 utils 메서드를 사용합니다.

public static final void vibratePhone(Context context, short vibrateMilliSeconds) {
    Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(vibrateMilliSeconds);
}

AndroidManifest 파일에 다음 권한을 추가하십시오.

<uses-permission android:name="android.permission.VIBRATE"/>

위에 제시된 것처럼 다양한 유형의 진동 (패턴 / 비 한정)을 사용하려는 경우 오버로드 된 방법을 사용할 수 있습니다.


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



출처: http://www.masterqna.com/android/48713/%EB%A7%A4%EB%84%88%EB%AA%A8%EB%93%9C%EC%97%90%EC%84%9C-soundpool%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%98%EC%97%AC-%EC%86%8C%EB%A6%AC%EB%82%98%EA%B2%8C%ED%95%98%EB%8A%94%EB%B0%A9%EB%B2%95


매너모드에서 soundpool를 이용하여 소리나게하는방법

매너모드에서 soundpool를 이용하여 매너모드에서도  소리가 나게하는방법 뭐가있나요

서비스로 전화온걸 감지하여 soundpool 로 출력하면 소리가 나지요...

잠금상태에서도 잠금을 풀고 메시지 박스 출력하면서 소리가 나게도 가능하구요

 

http://devbible.tistory.com/29

 

여기를 보시면 이런 내용이 있습니다

"단말기 상태가 진동이건 벨이건 무음이건 상관없이 어플에서 지정한데로 나온다."

 

충분히 가능하지요? ^^

 

---------------------------------



/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: http://devbible.tistory.com/29


AudioManager  mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

(수정) 2011-05-25
/* 현재 오디오모드확인 */
mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT : 사일런트 모드일 경우(값0)
mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE : 진동모드일 경우(값1)
mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL : 벨 모드일 경우(값2)
//AudioManager.ACTION_AUDIO_BECOMING_NOISY : 이어잭을 꼽고 있다가 뺏을 경우.

/* 오디오모드 셋팅 */
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);  //벨
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);  //진동
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); //무음

단말기 상태가 진동이건 벨이건 무음이건 상관없이 어플에서 지정한데로 나온다.
예를들어 단말기가 무음모드라고 해도 어플에서 소리를 내보내면 소리가 나게된다.
따라서 단말기의 모드를 확인 후에 그에 맞는 Effect를 해주는게 맞다.

[▼추가]
Android 에서 소리를 재생하는데에 앱에 특별히 필요한 권한 설정은 없지만.
진동을 울리기 위해서는 권한이 필요하다.

AndroidManifest.xml 에 밑에와 같이 권한을 넣어줘야만 하고
또 사용자가 앱 설치시에 이에 동의해야 한다.

<uses-permission android:name="android.permission.VIBRATE"/>



출처: http://devbible.tistory.com/29 [devbible]


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: https://www.androidpub.com/1112042




안녕하세요

2.2기반으로 진동 혹은 무음 모드 일 때 벨소리를 울리게 하려고 합니다.


int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume, 0);

alarmRingtone = ringtoneManager.getRingtone(mContext, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));
alarmRingtone.play();

위와 같은 소스를 만들었더니 진동 모드에서 벨소리가 한칸 상승합니다.

혹시나 싶어서 위 소스의 1,2번째 줄을

for(int i=1; i<=maxVolume; i++){
    mAudioManager.adjustStreamVolume(AudioManager.STREAM_ALARM,  AudioManager.ADJUST_RAISE, 0);
}

위와 같은 방법을 써봐도 역시나 진동 모드에서 벨소리가 한칸 상승합니다.

진동 모드에서도 우렁찬 소리를 뿜어줘야 하는데 비실비실한 소리만 제 마음을 아프게하네요.

어떤 방법을 써야 진동 모드에서도 우렁찬 벨소리가 나와줄까요?

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
commonlife
자답이에요

AudioManager.STREAM_ALARM 을 AudioManager.STREAM_RING 으로 바꿔주니 되는군요... ^^;;



///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



출처: http://codeticker.tistory.com/entry/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-sound-%EC%83%81%ED%83%9C-%EC%A0%9C%EC%96%B4%ED%95%98%EA%B8%B0


AudioManager aManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

오디오 매니저를 가져온 후


aManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);    //소리 켜기

aManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);    //진동모드

aManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);    //무음 모드


원하는 제어를 하면 된다.



출처: http://codeticker.tistory.com/entry/안드로이드-sound-상태-제어하기 [CodeTicker]

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

반응형
그리드형


관련글 더보기

댓글 영역