总结一下,停止声音文件的句子是:
AudioServicesDisposeSystemSoundID (soundFileObject);
解释(重要理解):
我有一个包含 18 个不同声音文件的表格视图。当用户选择一行时必须发出相应的文件,并且在选择另一行时,它必须停止前一个声音并播放其他。
所有这些东西都是必要的:
1)在“Build Phases”内的“Link Binary With Libraries”内添加到您的项目“AudioToolbox.framework”
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)”,因为当用户离开表格视图时应用程序意外结束。
所有这些代码都是由苹果公司按比例分配的。在此链接中,您甚至可以找到直接在 iPhone 模拟器中测试的示例代码。
https://developer.apple.com/library/ios/samplecode/SysSound/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008018-Intro-DontLinkElementID_2