要約すると、サウンド ファイルを停止する文は次のとおりです。
AudioServicesDisposeSystemSoundID (soundFileObject);
説明 (理解することが重要):
18 の異なるサウンド ファイルを含むテーブル ビューがあります。ユーザーが行を選択すると、対応するファイルを鳴らす必要があり、別の行を選択すると、前の音を停止して他の音を再生する必要があります。
このすべてが必要です:
1) プロジェクトに「AudioToolbox.framework」を「Build Phases」内の「Link Binary With Libraries」内に追加します。
2)ヘッダーファイル(私のプロジェクトでは「GenericTableView.h」と呼ばれます)に次の文を追加します:
#include <AudioToolbox/AudioToolbox.h>
CFURLRef soundFileURLRef;
SystemSoundID soundFileObject;
@property (readwrite) CFURLRef soundFileURLRef;
@property (readonly) SystemSoundID soundFileObject;
3)実装ファイル(私のプロジェクトでは「GenericTableView.m」と呼ばれます)に次の文を追加します。
@synthesize soundFileURLRef;
@synthesize soundFileObject;
そして、「アクション」実装内、または私の場合は、次のとおりです。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
//
// That is the question: a way to STOP sound file
//
// -----------------------------------------------------------------------
// Very important to STOP the sound file
AudioServicesDisposeSystemSoundID (soundFileObject);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// In my project "rowText" is a field that save the name of the
// corresponding sound (depending on row selected)
// It can be a string, @"Alarm Clock Bell" in example
// Create the URL for the source audio file.
// URLForResource:withExtension: method is new in iOS 4.0.
NSURL *soundURL = [[NSBundle mainBundle] URLForResource:rowText withExtension:@"caf"];
// Store the URL as a CFURLRef instance
self.soundFileURLRef = (CFURLRef) [soundURL retain];
// Create a system sound object representing the sound file.
AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject);
AudioServicesPlaySystemSound (soundFileObject);
[soundURL release];
}
4) 最後に、同じ実装ファイルで (私のプロジェクトでは "GenericTableView.m" を呼び出します):
- (void)dealloc {
[super dealloc];
AudioServicesDisposeSystemSoundID (soundFileObject);
//CFRelease (soundFileURLRef);
}
ユーザーがテーブルビューを離れるとアプリが予期せず終了するため、「CFRelease (soundFileURLRef)」にコメントする必要があります。
このコードはすべて Apple によって調整されます。このリンクでは、iPhone シミュレーターで直接テストするためのサンプル コードも見つけることができます。
https://developer.apple.com/library/ios/samplecode/SysSound/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008018-Intro-DontLinkElementID_2